package com.ybkj.daijia.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.CommonCons;
import com.ybkj.daijia.DateTimeUtils;
import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.common.Distance;
import com.ybkj.daijia.common.HtmlHelper;
import com.ybkj.daijia.common.OrderInfo;
import com.ybkj.daijia.common.Pager;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.AnnouncementEvent;
import com.ybkj.daijia.server.event.model.DriverJobTypeChangeEvent;
import com.ybkj.daijia.server.event.model.DriverPowerOfflineEvent;
import com.ybkj.daijia.server.event.model.DriverRechargeEvent;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.freight.Truck;
import com.ybkj.daijia.server.mapper.DriverMapper;
import com.ybkj.daijia.server.model.Announcement;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverChoseLevel;
import com.ybkj.daijia.server.model.DriverChoseLevelCar;
import com.ybkj.daijia.server.model.DriverChoseLevelFreight;
import com.ybkj.daijia.server.model.DriverChoseLevelPaotui;
import com.ybkj.daijia.server.model.DriverChoseLevelZhuanxian;
import com.ybkj.daijia.server.model.DriverLevel;
import com.ybkj.daijia.server.model.DriverLogin;
import com.ybkj.daijia.server.model.DriverLoginRecord;
import com.ybkj.daijia.server.model.DriverPaymentsRecord;
import com.ybkj.daijia.server.model.DriverRebate;
import com.ybkj.daijia.server.model.HelpPayRecord;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.OrderCarType;
import com.ybkj.daijia.server.model.PhoneRecord;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.service.AdminService;
import com.ybkj.daijia.server.service.AnnouncementService;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverChoseLevelCarService;
import com.ybkj.daijia.server.service.DriverChoseLevelFreightService;
import com.ybkj.daijia.server.service.DriverChoseLevelPaotuiService;
import com.ybkj.daijia.server.service.DriverChoseLevelService;
import com.ybkj.daijia.server.service.DriverChoseLevelZhuanxianService;
import com.ybkj.daijia.server.service.DriverConsumedRecordService;
import com.ybkj.daijia.server.service.DriverGradeService;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.DriverLevelService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverPaymentsRecordService;
import com.ybkj.daijia.server.service.DriverRebateService;
import com.ybkj.daijia.server.service.DriverRechargeRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandUpService;
import com.ybkj.daijia.server.service.FreightService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.PhoneRecordService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import com.ybkj.daijia.server.service.TrainService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.service.impl.DefaultDriverRebateService;
import com.ybkj.daijia.server.zhuan.Car;
import com.ybkj.daijia.server.zhuanxian.Line;
import com.ybkj.daijia.serverUtils.ExcelUtil;
import com.ybkj.daijia.serverUtils.FilterStrUtil;
import com.ybkj.daijia.serverUtils.HttpClientUtil;
import com.ybkj.daijia.serverUtils.QRCodeUtil;
import com.ybkj.daijia.serverUtils.RegExpValidatorUtils;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "driver")
@Slf4j
public class DriverController {

    public static final BigDecimal HUNDRED = BigDecimal.valueOf(100);
    @Autowired
    private DriverService driverService;
    @Autowired
    private DriverMapper driverMapper;
    @Autowired
    private DriverGradeService driverGradeService;
    @Autowired
    private DriverChoseLevelService driverChoseLevelService;
    @Autowired
    private DriverChoseLevelCarService driverChoseLevelCarService;
    @Autowired
    private PhoneRecordService phoneRecordService;
    @Autowired
    private DriverLevelService driverLevelService;
    @Autowired
    private DriverRechargeRecordService driverRechargeRecordService;
    @Autowired
    private DriverConsumedRecordService driverConsumedRecordService;
    @Autowired
    private DriverChoseLevelPaotuiService driverChoseLevelPaotuiService;
    @Autowired
    private DriverChoseLevelFreightService driverChoseLevelFreightService;
    @Autowired
    private DriverChoseLevelZhuanxianService driverChoseLevelZhuanxianService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private FreightService freightService;
    @Autowired
    private ErrandUpService errandService;
    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private TaskExecutor taskExecutor;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private AreaService areaService;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private DriverPaymentsRecordService driverPaymentsRecordService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private DriverLoginService driverLoginService;
    @Autowired
    private AnnouncementService announcementService;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private TrainService trainService;
    @Autowired
    private DriverHelppayService helppayService;
    @Autowired
    private DriverRebateService driverRebateService;
    @Autowired
    private DefaultDriverRebateService defaultDriverRebateService;

    @RequestMapping(value = "jump")
    public String jump() {
        Subject subject = SecurityUtils.getSubject();
        //服务人员
        if (subject.isPermitted("servicePersonal")) {
            return "redirect:/driver/list";
        }
        //服务人员等级
        else if (subject.isPermitted("drivergrade")) {
            return "redirect:/drivergrade/list";
        }
        //申请
        else if (subject.isPermitted("driverapply")) {
            return "redirect:/driverapply/list";
        }
        //通话记录
        else if (subject.isPermitted("callLog")) {
            return "redirect:/driver/recordlist";
        }
        //通知
        else if (subject.isPermitted("notice")) {
            return "redirect:/notice/list";
        }
        //公告
        else if (subject.isPermitted("announcement")) {
            return "redirect:/driver/announcementList";
        }
        //批量操作
        else if (subject.isPermitted("drivermoney")) {
            return "redirect:/driver/drivermoney";
        }
        //服务人员奖励
        else if (subject.isPermitted("drivermoney")) {
            return "redirect:/driver/driverReward";
        }
        //申请提现
        else if (subject.isPermitted("driverenchashment")) {
            return "redirect:/driverenchashment/list";
        }
        //登录日志
        else if (subject.isPermitted("driverloginrecord")) {
            return "redirect:/driver/loginlist";
        }
        return "";
    }

    @RequestMapping("daijiaListDrivers")
    public @ResponseBody
    List<Driver> daijiaListDrivers(
        @RequestParam(required = true, value = "lng") Double lng,
        @RequestParam(required = true, value = "lat") Double lat,
        @RequestParam(required = true, value = "distance") Double distance) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("order")) {
            return driverService.daijiaListDrivers(lng, lat, distance);
        } else {
            throw new NoPermissionException();
        }
    }

    // 可以做专车业务的服务人员
    @RequestMapping("zhuanListDrivers")
    public @ResponseBody
    List<Driver> zhuanListDrivers(
        @RequestParam(required = true, value = "orderId") Long orderId,
        @RequestParam(required = true, value = "lng") Double lng,
        @RequestParam(required = true, value = "lat") Double lat,
        @RequestParam(required = true, value = "distance") Double distance) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuan")) {
            com.ybkj.daijia.server.zhuan.Order order = zhuancheService.findOne(orderId);
            List<Driver> list = driverService.zhuanListDrivers(lng, lat, distance,
                order.getPassengerId(), order.getCarTypeId());
            return list;
        } else {
            throw new NoPermissionException();
        }
    }

    // 可以做货运业务的服务人员
    @RequestMapping("freightListDrivers")
    public @ResponseBody
    List<Driver> freightListDrivers(
        @RequestParam(required = true, value = "orderId") Long orderId,
        @RequestParam(required = true, value = "lng") Double lng,
        @RequestParam(required = true, value = "lat") Double lat,
        @RequestParam(required = true, value = "distance") Double distance) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("freight")) {
            List<Driver> list = driverService.freightListDrivers(lng, lat, distance);
            com.ybkj.daijia.server.freight.Order order = freightService.findOne(orderId);

            Long typeId = null;// 订单的货运车辆类型id
            if (order != null) {
                typeId = order.getTruckTypeId();
            }
            List<Driver> drivers = new ArrayList<Driver>();
            for (Driver driver : list) {
                Long truckId = driver.getTruckId();
                if (truckId != null) {
                    Truck truck = freightService.findTruck(truckId);
                    Long truckTypeId = null;// 服务人员所开的货运车辆类型id
                    if (truck != null) {
                        truckTypeId = truck.getTruckTypeId();
                    }
                    if (typeId != null && truckTypeId != null && truckTypeId.equals(typeId)) {
                        drivers.add(driver);
                    }
                }
            }
            return drivers;
        } else {
            throw new NoPermissionException();
        }
    }

    // 可以做跑腿业务的服务人员
    @RequestMapping("errandListDrivers")
    public @ResponseBody
    List<Driver> errandListDrivers(
        @RequestParam(required = true, value = "lng") Double lng,
        @RequestParam(required = true, value = "lat") Double lat,
        @RequestParam(required = true, value = "distance") Double distance) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("errandPaidan")) {
            List<Driver> list = driverService.errandListDrivers(lng, lat, distance);

            return list;
        } else {
            throw new NoPermissionException();
        }
    }

    // 可以做城际专线业务的服务人员
    @RequestMapping("zhuanxianListDrivers")
    public @ResponseBody
    List<Driver> zhuanxianListDrivers(
        @RequestParam(required = true, value = "orderId") Long orderId,
        @RequestParam(required = true, value = "lng") Double lng,
        @RequestParam(required = true, value = "lat") Double lat,
        @RequestParam(required = true, value = "distance") Double distance) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("zhuanxianPaidan")) {
            List<Driver> list = driverService.zhuanxianListDrivers(lng, lat, distance);
            com.ybkj.daijia.server.zhuanxian.Order order = zhuanxianService.findOne(orderId);

            Long lineId = order.getLineId();

            List<Driver> drivers = new ArrayList<Driver>();

            if (!CollectionUtils.isEmpty(list)) {
                for (Driver driver : list) {
                    if (null != driver.getZhuanxianCarId()) {
                        com.ybkj.daijia.server.zhuanxian.Car car = zhuanxianService.findCar(driver
                            .getZhuanxianCarId());
                        if (null != car && !CollectionUtils.isEmpty(car.getLines())) {
                            Line line = car.getLines().get(0);
                            boolean success = zhuanxianService
                                .isReceiveAnOrder(order.getPeopleNumber(),
                                    order.getOrderType(), driver.getId());
                            if (!success) {
                                continue;
                            }
                            if (line.getId().equals(lineId)) {
                                drivers.add(driver);
                            }
                        }
                    }
                }
            }

            return drivers;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "queryByKey")
    public @ResponseBody
    Object queryByKey(@RequestParam("keyword") String keyword,
        @RequestParam(required = false, value = "orderId") Long orderId) {

        Order order = orderService.findOne(orderId);

        List<Driver> drivers = driverService.queryByKeyword(keyword);

        List<Map<String, Object>> list = new LinkedList<Map<String, Object>>();

        if (!CollectionUtils.isEmpty(drivers)) {

            for (Driver driver : drivers) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("driverID", driver.getId());
                map.put("driverName", driver.getRealname());
                map.put("driverPhone", driver.getPhone());
                map.put(
                    "distance",
                    Distance.doubleVal(order.getClientLatitude(), order.getClientLongitude(),
                        driver.getLatitude(), driver.getLongitude()));
                list.add(map);
            }

        }

        return list;
    }

    @RequestMapping(value = "list2", method = RequestMethod.GET)
    public ModelAndView list2(@RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "status") Integer status,
        @RequestParam(required = false, value = "type") Integer type) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/list2");

            mv.addObject("page", driverService.queryAll(param, status, type));

            mv.addObject("param", param);
            mv.addObject("status", status);
            mv.addObject("type", type);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "lesslist", method = RequestMethod.GET)
    public ModelAndView lesslist(@RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/lesslist");

            mv.addObject("page", driverService.queryLessList(param));
            mv.addObject("param", param);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "freezelist", method = RequestMethod.GET)
    public ModelAndView freezelist(@RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/freezelist");

            mv.addObject("page", driverService.queryFreezeList(param));
            mv.addObject("param", param);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "drivermoney", method = RequestMethod.GET)
    public ModelAndView drivermoney() {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("drivermoney")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/drivermoney");
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "announcementAdd", method = RequestMethod.GET)
    public ModelAndView announcement() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("announcement")) {
            ModelAndView mv = new ModelAndView();
            Principal principal = (Principal) subject.getPrincipal();
            if (principal.isCompanyType()) {
                List<Company> list = companyService.findAll();
                mv.addObject("companys", list);
            }
            mv.setViewName("driver/announcementAdd");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "announcement", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> announcement(
        @RequestParam(required = false, value = "companyId") Long companyId,
        @RequestParam(required = true, value = "title") String title,
        @RequestParam(required = true, value = "content") String content) {

        Subject subject = SecurityUtils.getSubject();

        Setting setting = settingUtils.get();

        if (subject.isPermitted("announcement")) {
            Map<String, Object> map = new HashMap<String, Object>();
            try {

                String companyName = "所有公司";
                Principal principal = (Principal) subject.getPrincipal();

                if (!principal.isCompanyType()) {
                    companyId = principal.getCompanyId();
                    companyName = principal.getCompanyAbbreviation();
                }

                if (null != companyId) {
                    Company comapny = companyService.findOne(companyId);
                    companyName = comapny.getAbbreviation();
                }

                // 判断是否有过滤字段
                String filterStr = setting.getFilterStr();
                if (StringUtils.isNotBlank(filterStr)) {
                    String content1 = title;
                    String content2 = null;
                    if (StringUtils.isNotBlank(content)) {
                        content2 = HtmlHelper.html2Text(content);
                    }
                    if (StringUtils.isNotBlank(content1)) {
                        boolean c1 = FilterStrUtil.check(content1, filterStr);
                        if (!c1) {
                            map.put("success", false);
                            map.put("message", "发布内容含有违规信息。");
                            return map;
                        }
                    }
                    if (StringUtils.isNotBlank(content2)) {
                        boolean c2 = FilterStrUtil.check(content2, filterStr);
                        if (!c2) {
                            map.put("success", false);
                            map.put("message", "发布内容含有违规信息。");
                            return map;
                        }
                    }
                }

                String html2Text = HtmlHelper.html2Text(content);
                if (html2Text.length() > 10000) {
                    map.put("success", false);
                    map.put("message", "公告内容过长,不能超过1万字符");
                    return map;
                }

                Announcement announcement = announcementService.create(title, content, companyId,
                    principal.getUsername(), companyName);

                List<Driver> drivers = new ArrayList<Driver>();

                if (null == companyId) {
                    drivers = driverService.findAll();
                } else {
                    drivers = driverService.findAllByCompanyId(companyId);
                }

                // 推送
                AnnouncementEvent announcementEvent = new AnnouncementEvent(announcement, drivers);
                applicationEventMulticaster.multicastEvent(announcementEvent);

                map.put("success", true);
                map.put("message", "发布成功");

            } catch (Exception e) {
                e.printStackTrace();
                map.put("success", false);
                map.put("message", "发布失败!");
            }
            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "announcement/delete", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> announcementDelete(
        @RequestParam(required = true, value = "id") Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("announcement")) {
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                announcementService.delete(id);
                map.put("success", true);
                map.put("message", "公告删除成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return map;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("announcementLook/{id}")
    public ModelAndView look(@PathVariable("id") Long id) {

        ModelAndView mv = new ModelAndView();

        Announcement announcement = announcementService.findOne(id);

        mv.addObject("announcement", announcement);

        mv.setViewName("driver/announcementLook");

        return mv;
    }

    @RequestMapping(value = "announcementList", method = RequestMethod.GET)
    public ModelAndView announcementList() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("announcement")) {
            Principal principal = (Principal) subject.getPrincipal();
            ModelAndView mv = new ModelAndView();
            Page<Announcement> page = null;
            if (principal.isCompanyType()) {
                page = announcementService.queryAll();
            } else {
                page = announcementService.findByCompanyId(principal.getCompanyId());
            }
            mv.addObject("page", page);
            mv.setViewName("driver/announcementList");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * @param money
     * @param memo
     * @param drivers
     * @return
     */
    @RequestMapping(value = "driverMoney", method = RequestMethod.POST)
    public ModelAndView driverMoney(
        @RequestParam(required = true, value = "money") BigDecimal money,
        @RequestParam(required = true, value = "memo") String memo,
        @RequestParam(required = true, value = "drivers") Long[] drivers) {
        ModelAndView mv = new ModelAndView();
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("drivermoney")) {
            List<Driver> driverList = new ArrayList<Driver>();
            if (null != drivers && drivers.length > 0) {
                for (Long driverId : drivers) {
                    Driver driver = driverService.findOne(driverId);
                    if (driver != null) {
                        driverList.add(driver);
                    }
                }
            }
            try {
                Setting setting = settingUtils.get();

                for (Driver driver : driverList) {

                    driver.setVirtual(driver.getVirtual().add(money));
                    driverService.updateVirtual(driver);

                    //批量充值$$$
                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(money);
                    driverPaymentsRecord.setMemo(memo);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    if (driverPaymentsRecord.getMoney().doubleValue() > 0) {
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_ADMIN);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                    } else {
                        driverPaymentsRecord.setMoney(driverPaymentsRecord.getMoney().negate());
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.CONSUMED_TYPE_ADMIN);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_NEGATIVE);
                    }
                    driverPaymentsRecord.setOperating(principal.getUsername());
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordService.insertRecord(driverPaymentsRecord);

                    HelpPayRecord helpPayRecord = new HelpPayRecord();
                    helpPayRecord.setChangeMoney(money);
//                    helpPayRecord.setPaymentRecordId(driverPaymentsRecord.getId());
                    helpPayRecord.setDriverId(driver.getId());
                    helpPayRecord.setOperateType(HelpPayRecord.BATCH_RECHARGE);
                    helpPayRecord.setMemo(
                        principal.getUsername() + "[" + principal.getId() + "]为司机[" + driver.getId()
                            + "] 充值" + money +
                            "元");
                    helppayService.operateDriverMoney(helpPayRecord);

                    String detail =
                        "【%s】为服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】充值"
                            + money + "，备注：" + memo;

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    ReactorVo rVo = new ReactorVo();
                    rVo.setDriver(driver);
                    rVo.setMoney(money);
                    rVo.setType("admin");
                    DriverRechargeEvent rechargeEvent = new DriverRechargeEvent(rVo);
                    applicationEventMulticaster.multicastEvent(rechargeEvent);

                    if (driver.getStatus().equals(Driver.DRIVER_ONLINE)
                        && driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
                        && setting.getLowestWorkVirtual() != 0
                        && driver.getVirtual().doubleValue() < setting.getLowestWorkVirtual()) {

                        driverService.updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

                        DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(
                            driver,
                            Driver.DRIVER_ONLINE, "sys");
                        applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            mv.setViewName("driver/list");
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            } else {
                mv.addObject("companys", companyService.findOne(principal.getCompanyId()));
            }
            //zhyu:看见freemaker 报错, 不知道该不该添加
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            Boolean isJgpt = serviceSetting.isJgpt();
            mv.addObject("isJgpt", isJgpt);
            if (isJgpt) {
                mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
            } else {
                mv.addObject("isUpPlatformInfo", false);
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "queryDrivers", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> queryDrivers(
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "virtual") BigDecimal virtual,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "companyId") Long[] companyId,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "freeze") Boolean freeze,
        @RequestParam(required = false, value = "type") String[] type,
        @RequestParam(required = false, value = "jobType") String[] jobType) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", true);
        Date start = null;
        Date end = null;
        if (!StringUtils.isEmpty(startTime)) {
            try {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(start);
                calendar.set(Calendar.HOUR_OF_DAY, 0);
                calendar.set(Calendar.MINUTE, 0);
                calendar.set(Calendar.SECOND, 0);

                start = calendar.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        if (!StringUtils.isBlank(endTime)) {
            try {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd");

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(end);
                calendar.set(Calendar.HOUR_OF_DAY, 23);
                calendar.set(Calendar.MINUTE, 59);
                calendar.set(Calendar.SECOND, 59);

                end = calendar.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (null != companyId && companyId.length == 0) {
            companyId = null;
        }
        if (null != type && type.length == 0) {
            type = null;
        }
        if (null != status && status.length == 0) {
            status = null;
        }
        if (null != jobType && jobType.length == 0) {
            jobType = null;
        }

        List<Driver> list = driverService.selectDriverList(name, phone, username, start, end,
            companyId, virtual, freeze, type, status, null, jobType);

        map.put("count", list.size());
        map.put("driverList", list);
        return map;
    }

    @RequestMapping(value = "driverReward", method = RequestMethod.GET)
    public ModelAndView driverReward() {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("drivermoney")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/driverreward");
            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    //$$
    @RequestMapping(value = "driverReward", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> driverMoney(
        @RequestParam(required = true, value = "drivers") Long[] drivers,
        @RequestParam(required = true, value = "money") BigDecimal[] money,
        @RequestParam(required = true, value = "memo") String memo, HttpSession session) {

        Map<String, Object> map = new HashMap<String, Object>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("drivermoney")) {
            String returnMessage = "";
            for (int i = 0; i < drivers.length; i++) {
                Driver driver = driverService.findOne(drivers[i]);
                try {
                    driver.setVirtual(driver.getVirtual().add(money[i]));
                    driverService.updateVirtual(driver);

                    DriverPaymentsRecord driverPaymentsRecord = new DriverPaymentsRecord();
                    driverPaymentsRecord.setMoney(money[i]);
                    driverPaymentsRecord.setMemo("服务人员奖励。" + memo);
                    driverPaymentsRecord.setAfterMoney(driver.getVirtual());
                    driverPaymentsRecord.setDriverId(driver.getId());
                    driverPaymentsRecord.setDriverRealName(driver.getRealname());
                    driverPaymentsRecord.setDriverUserName(driver.getUsername());
                    driverPaymentsRecord.setDriverPhone(driver.getPhone());
                    driverPaymentsRecord.setDriverCompanyId(driver.getCompanyId());
                    if (driverPaymentsRecord.getMoney().doubleValue() > 0) {
                        driverPaymentsRecord
                            .setRecordType(DriverPaymentsRecord.RECHARGE_TYPE_REWARD);
                        driverPaymentsRecord.setRcType(DriverPaymentsRecord.DIFFERENT_POSITIVE);
                    }
                    driverPaymentsRecord.setOperating(principal.getUsername());
                    driverPaymentsRecord.setHappend(new Date());
                    driverPaymentsRecordService.insertRecord(driverPaymentsRecord);

                    session.setAttribute("rewardProcess",
                        Double.valueOf(i + 1) / Double.valueOf(drivers.length));

                    String detail =
                        "【%s】为服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】奖励"
                            + money[i] + "元。" + memo;
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                } catch (Exception e) {
                    returnMessage += "失败【" + driver.getRealname() + "】";
                    e.printStackTrace();
                }
            }

            session.removeAttribute("rewardProcess");

            map.put("success", true);
            map.put("errorMessage", returnMessage);
            return map;

        } else {
            map.put("success", false);
            map.put("message", "您没有该权限");
            return map;
        }
    }

    @RequestMapping(value = "getRewardProcess", method = RequestMethod.GET)
    public @ResponseBody
    Object getRewardProcess(HttpSession session) {
        return session.getAttribute("rewardProcess");
    }

    @RequestMapping(value = "getRewardDrivers", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getRewardDrivers(
        @RequestParam(required = false, value = "companyIds") Long[] companyIds,
        @RequestParam(required = true, value = "orderType") String orderType,
        @RequestParam(required = true, value = "finishAmounts") Long finishAmounts,
        @RequestParam(required = true, value = "lowestMoney") BigDecimal lowestMoney,
        @RequestParam(required = false, value = "start") String startTime,
        @RequestParam(required = false, value = "end") String endTime,
        @RequestParam(required = true, value = "rewardType") String rewardType,
        @RequestParam(required = false, value = "guding") BigDecimal guding,
        @RequestParam(required = false, value = "percent") Long percent) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Date start = null;
        Date end = null;

        if (!StringUtils.isEmpty(startTime)) {
            try {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd HH:mm");
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        if (!StringUtils.isBlank(endTime)) {
            try {
                end = DateUtils.parseDate(endTime, "yyyy-MM-dd HH:mm");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (!principal.isCompanyType()) {
            companyIds = new Long[1];
            companyIds[0] = principal.getCompanyId();
        }

        List<Driver> list = driverService.selectDriverList(null, null, null, null, null, companyIds,
            null, null, null, null, null, null);
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();

        if (!CollectionUtils.isEmpty(list)) {
            for (Driver driver : list) {
                Integer trueFinishAmounts = 0;
                BigDecimal rewardMoney = BigDecimal.ZERO;
                if (rewardType.equals("guding")) {
                    rewardMoney = guding;
                }
                if (orderType.equals("daijia")) {
                    List<Order> daijiaList = orderService
                        .findReward(driver.getId(), lowestMoney, start, end);
                    if (!CollectionUtils.isEmpty(daijiaList)) {
                        trueFinishAmounts = daijiaList.size();
                        if (rewardType.equals("percent")) {
                            for (Order order : daijiaList) {
                                rewardMoney = rewardMoney.add(order.getRealCash());
                            }
                            rewardMoney = rewardMoney.multiply(new BigDecimal(percent))
                                .divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                } else if (orderType.equals("zhuanche")) {
                    List<com.ybkj.daijia.server.zhuan.Order> zhuancheList = zhuancheService
                        .findReward(
                            driver.getId(), lowestMoney, start, end);
                    if (!CollectionUtils.isEmpty(zhuancheList)) {
                        trueFinishAmounts = zhuancheList.size();
                        if (rewardType.equals("percent")) {
                            for (com.ybkj.daijia.server.zhuan.Order order : zhuancheList) {
                                rewardMoney = rewardMoney.add(new BigDecimal(order.getRealPay()));
                            }
                            rewardMoney = rewardMoney.multiply(new BigDecimal(percent))
                                .divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                } else if (orderType.equals("errand")) {
                    List<com.ybkj.daijia.server.errand.OrderUp> errandList = errandService
                        .findReward(
                            driver.getId(), lowestMoney, start, end);
                    if (!CollectionUtils.isEmpty(errandList)) {
                        trueFinishAmounts = errandList.size();
                        if (rewardType.equals("percent")) {
                            for (com.ybkj.daijia.server.errand.OrderUp order : errandList) {
                                rewardMoney = rewardMoney.add(new BigDecimal(order.getRealPay()));
                            }
                            rewardMoney = rewardMoney.multiply(new BigDecimal(percent))
                                .divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                } else if (orderType.equals("freight")) {
                    List<com.ybkj.daijia.server.freight.Order> freightList = freightService
                        .findReward(
                            driver.getId(), lowestMoney, start, end);
                    if (!CollectionUtils.isEmpty(freightList)) {
                        trueFinishAmounts = freightList.size();
                        if (rewardType.equals("percent")) {
                            for (com.ybkj.daijia.server.freight.Order order : freightList) {
                                rewardMoney = rewardMoney.add(new BigDecimal(order.getRealPay()));
                            }
                            rewardMoney = rewardMoney.multiply(new BigDecimal(percent))
                                .divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
                        }
                    }
                }

                if (trueFinishAmounts >= finishAmounts) {
                    Map<String, Object> dataMap = new HashMap<>();
                    dataMap.put("driverId", driver.getId());
                    dataMap.put("driverRealName", driver.getRealname());
                    dataMap.put("rewardMoney", rewardMoney);
                    dataMapList.add(dataMap);
                }

            }
        }

        return dataMapList;
    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(HttpSession session) {

        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();

            if (subject.isPermitted("driveradd")) {

                ModelAndView mv = new ModelAndView();

                if (subject.isPermitted("otherdriverlevel")) {
                    Company thisCompany = companyService.findOne(principal.getCompanyId());

                    List<Company> companys = new ArrayList<Company>();
                    if (principal.isCompanyType()) {
                        companys = companyService.findByAreaCityName(null);
                    } else {
                        companys = companyService.findByAreaCityName(thisCompany.getCityName());
                    }
                    for (Company company : companys) {
                        company.setDriverLevels(driverLevelService.listByCompany(company.getId()));
                        if (principal.getCompanyId() == company.getId()) {
                            company.setSort(1);
                        }
                    }
                    mv.addObject("detailedJobType",
                        errandService.queryOrderType(principal.getCompanyId()));
                    mv.addObject("companys", companys);
                } else {
                    List<Company> companys = new ArrayList<Company>();
                    companys.add(companyService.findOne(principal.getCompanyId()));
                    mv.addObject("detailedJobType",
                        errandService.queryOrderType(principal.getCompanyId()));
                    for (Company company : companys) {
                        company.setDriverLevels(driverLevelService.listByCompany(company.getId()));
                    }
                    mv.addObject("companys", companys);
                }

                mv.addObject("companyId", principal.getCompanyId());
                mv.addObject("driverGrades", driverGradeService.findAll());
                //自动生成新的工号
                mv.addObject("newUsername", driverService.findLastestDriver());
                mv.addObject("driver", new Driver());
                ServiceSetting serviceSetting = ServiceUtil.checkOpen();
                if (serviceSetting.isJgpt()) {
                    mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
                } else {
                    mv.addObject("isUpPlatformInfo", false);
                }

                mv.setViewName("driver/add");

                return mv;
            } else {
                throw new NoPermissionException();
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Driver> create(Driver driver, Long carId, Long truckId,
        Long zhuanxianCarId, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Driver> result = new Result<Driver>();
        result.setSuccess(false);

        if (null != carId) {
            Driver findByCarId = driverService.findByCarId(carId);
            if (null != findByCarId) {// 车辆已有司机绑定，清除之前司机的专车信息
                // Car car = zhuancheService.findCar(carId);
                // result.setMessage("所选车辆'" + car.getCarNumber() + "'已被占用");
                // return result;
                driverService.updateDriverCarId(findByCarId.getId(), null);
            }
        }
        if (null != truckId) {
            Driver findByCarId = driverMapper.selectByTruckId(truckId);
            if (null != findByCarId) {
                Truck truck = freightService.findTruck(truckId);
                result.setMessage("所选车辆'" + truck.getCarNumber() + "'已被占用");
                return result;
            }
        }
        if (null != zhuanxianCarId) {
            Driver findByCarId = driverMapper.selectByZhuanxianCarId(zhuanxianCarId);
            if (null != findByCarId) {
                com.ybkj.daijia.server.zhuanxian.Car car = zhuanxianService.findCar(zhuanxianCarId);
                result.setMessage("所选车辆'" + car.getCarNumber() + "'已被占用");
                return result;
            }
        }
        if (subject.isPermitted("driveradd")) {
            if (exists(driver.getUsername(), null)) {
                result.setMessage("工号'" + driver.getUsername() + "'已存在");
                return result;
            }
            if (idCardExists(driver.getIdCard(), null)) {
                result.setMessage("身份证'" + driver.getIdCard() + "'已存在");
                return result;
            }
            if (phoneExists(driver.getPhone(), null)) {
                result.setMessage("手机号'" + driver.getPhone() + "'已存在");
                return result;
            }

            Company company = companyService.findOne(principal.getCompanyId());
            driver.setCompanyId(principal.getCompanyId());
            driver.setDriveTimes(0);
            driver.setIsFreeze(false);
            driver.setStatus(Driver.DRIVER_OFFLINE);
            driver.setVirtual(BigDecimal.ZERO);
            driver.setLongitude(company.getLongitude());
            driver.setLatitude(company.getLatitude());
            driver.setNamePinyin(toPinyin(driver.getRealname()));
            driver.setJobTime(new Date());
            driver.setCarId(carId);
            driver.setTruckId(truckId);
            driver.setZhuanxianCarId(zhuanxianCarId);
            driver.setDetailedJobType(driver.getDetailedJobType());
            String idCard = driver.getIdCard();
            String password = idCard.substring(idCard.length() - 4, idCard.length());
            log.debug("密码" + password);
            Sha256Hash hash = new Sha256Hash(String.valueOf(password));
            driver.setPassword(hash.toBase64());

            driverService.insertRecord(driver);

            if (null != carId) {
                zhuancheService.updateCar(carId, null, null, null, null, null, null, null, null,
                    driver.getId(), driver.getUsername() + " " + driver.getPhone(), null, null,
                    null);
            }
            if (null != truckId) {
                freightService.updateTruck(truckId, null, null, null, null, null, null, null,
                    driver.getId(), driver.getRealname() + " " + driver.getPhone());
            }
            if (null != zhuanxianCarId) {
                zhuanxianService.updateCar(zhuanxianCarId, null, null, null, null, null, null,
                    driver.getId(), driver.getRealname() + " " + driver.getPhone(), null);
            }
            String detail =
                "【%s】新增了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            Company finalCompany = driverCompany;
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            if (!main.getId().equals(driverCompany.getId()) && setting.isSmsMainCompany()) {
                finalCompany = main;
            }
            JSONObject smsParam = new JSONObject();
            smsParam.put("name", driver.getName());
            smsParam.put("company", company.getAbbreviation());
            smsParam.put("user", driver.getUsername());
            smsParam.put("password", password);
            try {
                String chenghu = "先生";
                if (driver.getGender().equals("女")) {
                    chenghu = "女士";
                }
                SmsTemplet templet = smsService
                    .findByAlias(finalCompany.getId(), SmsType.driverCreate);
                if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
//                    smsService.sendSms(driver.getPhone(), "driverCreate", "{\"服务人员名\":\"" + driver.getName()
//                                    + "\",\"称呼\":\"" + chenghu + "\",\"公司名\":\"" + company.getAbbreviation()
//                                    + "\",\"服务人员账号\":\"" + driver.getUsername() + "\",\"密码\":\"" + password + "\"}",
//                            finalCompany.getId(), 0, finalCompany.getSignName());
                    smsService.sendSms(driver.getPhone(), templet.getTemplateId(),
                        smsParam.toJSONString(), finalCompany.getId(), 0,
                        finalCompany.getSignName());
                }
            } catch (Exception e) {

            }

            result.setSuccess(true);
            return result;

        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    /**
     * 查询公司提成
     *
     * @return
     */
    @RequestMapping("queryLevels")
    @ResponseBody
    public List<DriverLevel> queryLevels(
        @RequestParam(value = "isMainCompany", required = false) Boolean isMainCompany,
        @RequestParam(value = "companyId", required = false) Long companyId) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Company company = companyService.findOne(principal.getCompanyId());
        List<DriverLevel> levels = new ArrayList<>();
        //判断是否是主公司
        if (company.isCompanyType()) {
            levels = driverLevelService.listAll();
        } else {
            levels = driverLevelService.listMyAll();
        }
        return levels;
    }

    /**
     * 批量修改司机部分数据
     *
     * @param tixian       是否允许申请提现
     * @param tuiguang     是否允许推广奖励
     * @param driverRebate 推荐百分比
     * @param zcDeductId   专车提成
     * @param zxpcDeductId 专线拼车提成
     * @param zxbcDeductId 专线包车提成
     * @param zxjhDeductId 专线寄货提成
     * @param drivers      司机id
     */
    @RequestMapping(value = "updateSomeDrivers", method = RequestMethod.POST)
    @ResponseBody
    public void updateSomeDrivers(@RequestParam("tixian") Integer tixian,
        @RequestParam("tuiguang") Integer tuiguang,
        @RequestParam(value = "driverRebate", required = false) Integer driverRebate,
        @RequestParam(value = "zcDeduct", required = false) Long zcDeductId,
        @RequestParam(value = "zxpcDeduct", required = false) Long zxpcDeductId,
        @RequestParam(value = "zxbcDeduct", required = false) Long zxbcDeductId,
        @RequestParam(value = "zxjhDeduct", required = false) Long zxjhDeductId,
        @RequestParam("drivers") Long[] drivers) {
        if (drivers.length > 0) {
            for (int i = 0; i < drivers.length; i++) {
                //修改提现、推广开关
                Driver driver = driverService.findOne(drivers[i]);
                if (null != tixian) {
                    driver.setTixian(tixian);
                }
                if (null != tuiguang) {
                    driver.setTuiguang(tuiguang);
                }
                driverService.updateDriverTxAndTg(driver);

                //修改推荐百分比
                if (null != driverRebate) {
                    DriverRebate byDriverId = driverRebateService.findByDriverId(driver.getId());
                    if (null != byDriverId) {
                        byDriverId.setCommission1(new BigDecimal(driverRebate));
                        byDriverId.setUpdated(new Date());
                        driverRebateService.update(byDriverId);
                    } else {
                        byDriverId = new DriverRebate();
                        byDriverId.setDriverId(driver.getId());
                        byDriverId.setType(DriverRebate.FIX_TYPR);
                        byDriverId.setLevel(DriverRebate.FIX_LEVEL);
                        byDriverId.setDriverRebateType1(DriverRebate.DriverRebateType.percent);
                        byDriverId.setCreated(new Date());
                        driverRebateService.save(byDriverId);
                    }
                }
                //修改专车提成

                //修改专线提成
                //拼车提成 lineType为0
                if (null != zxpcDeductId) {
                    driverChoseLevelZhuanxianService.deleteByDriverAndLine(driver.getId(), 0);
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian = new DriverChoseLevelZhuanxian();
                    driverChoseLevelZhuanxian.setDriverId(driver.getId());
                    driverChoseLevelZhuanxian.setDriverlevelId(zxpcDeductId);
                    driverChoseLevelZhuanxian.setLineType(0);
                    driverChoseLevelZhuanxianService.insertRecord(driverChoseLevelZhuanxian);
                }
                //包车提成 lineType为1
                if (null != zxbcDeductId) {
                    driverChoseLevelZhuanxianService.deleteByDriverAndLine(driver.getId(), 1);
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian = new DriverChoseLevelZhuanxian();
                    driverChoseLevelZhuanxian.setDriverId(driver.getId());
                    driverChoseLevelZhuanxian.setDriverlevelId(zxbcDeductId);
                    driverChoseLevelZhuanxian.setLineType(1);
                    driverChoseLevelZhuanxianService.insertRecord(driverChoseLevelZhuanxian);
                }
                //寄货提成 lineType为2
                if (null != zxjhDeductId) {
                    driverChoseLevelZhuanxianService.deleteByDriverAndLine(driver.getId(), 2);
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian = new DriverChoseLevelZhuanxian();
                    driverChoseLevelZhuanxian.setDriverId(driver.getId());
                    driverChoseLevelZhuanxian.setDriverlevelId(zxjhDeductId);
                    driverChoseLevelZhuanxian.setLineType(2);
                    driverChoseLevelZhuanxianService.insertRecord(driverChoseLevelZhuanxian);
                }
            }
        }


    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(HttpServletRequest req, @PathVariable("id") Long id) {

        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();

            if (subject.isPermitted("driver")) {
                /** 查询司机信息 */
                Driver local = driverService.findOne(id);
                local.setPhone(UseAllDataUtil.useAllDataDriver(local.getPhone()));
                if (null != local.getIdCardPhoto()) {
                    local.setIdCardPhoto(local.getIdCardPhoto().replace(",", ""));
                }
                ModelAndView mv = new ModelAndView();

                List<Company> companys = new ArrayList<Company>();
                if (subject.isPermitted("otherdriverlevel")) {
                    Company thisCompany = companyService.findOne(principal.getCompanyId());

                    if (principal.isCompanyType()) {
                        companys = companyService.findByAreaCityName(null);
                    } else {
                        companys = companyService.findByAreaCityName(thisCompany.getCityName());
                    }

                    for (Company company : companys) {
                        company.setDriverLevels(driverLevelService.listByCompany(company.getId()));
                        if (principal.getCompanyId() == company.getId()) {
                            company.setSort(1);
                        } else if (local.getCompanyId() == company.getId()) {
                            company.setSort(2);
                        }
                    }

                } else {
                    companys.add(companyService.findOne(principal.getCompanyId()));
                    for (Company company : companys) {
                        company.setDriverLevels(driverLevelService.listByCompany(company.getId()));
                        if (principal.getCompanyId() == company.getId()) {
                            company.setSort(1);
                        } else if (local.getCompanyId() == company.getId()) {
                            company.setSort(2);
                        }
                    }
                }
                for (Company company : companys) {
                    if (!CollectionUtils.isEmpty(company.getDriverLevels())) {
                        for (DriverLevel driverLevel : company.getDriverLevels()) {

                            DriverChoseLevel driverChoseLevel = driverChoseLevelService
                                .findByDriverAndLevelAndCompany(id, driverLevel.getId(), null);
                            if (null != driverChoseLevel) {
                                driverLevel.setDriverChecked(true);
                            } else {
                                driverLevel.setDriverChecked(false);
                            }

                            DriverChoseLevelCar driverChoseLevelCar = driverChoseLevelCarService
                                .findByDriverAndLevelAndCompany(id, driverLevel.getId(), null);
                            if (null != driverChoseLevelCar) {
                                driverLevel.setDriverCarChecked(true);
                            } else {
                                driverLevel.setDriverCarChecked(false);
                            }

                            DriverChoseLevelPaotui driverChoseLevelPaotui = driverChoseLevelPaotuiService
                                .findByDriverAndLevelAndCompany(id, driverLevel.getId(), null);
                            if (null != driverChoseLevelPaotui) {
                                driverLevel.setDriverPaotuiChecked(true);
                            } else {
                                driverLevel.setDriverPaotuiChecked(false);
                            }

                            DriverChoseLevelFreight driverChoseLevelFreight = driverChoseLevelFreightService
                                .findByDriverAndLevelAndCompany(id, driverLevel.getId(), null);
                            if (null != driverChoseLevelFreight) {
                                driverLevel.setDriverFreightChecked(true);
                            } else {
                                driverLevel.setDriverFreightChecked(false);
                            }

                        }
                    }
                    DriverChoseLevel driverChoseLevel = driverChoseLevelService
                        .findByDriverAndLevelAndCompany(id, 0L, company.getId());
                    DriverChoseLevelCar driverChoseLevelCar = driverChoseLevelCarService
                        .findByDriverAndLevelAndCompany(id, 0L, company.getId());
                    DriverChoseLevelPaotui driverChoseLevelPaotui = driverChoseLevelPaotuiService
                        .findByDriverAndLevelAndCompany(id, 0L, company.getId());
                    DriverChoseLevelFreight driverChoseLevelFreight = driverChoseLevelFreightService
                        .findByDriverAndLevelAndCompany(id, 0L, company.getId());
                    if (null != driverChoseLevel) {
                        company.setUseMine(true);
                    }
                    if (null != driverChoseLevelCar) {
                        company.setUseMineCar(true);
                    }
                    if (null != driverChoseLevelPaotui) {
                        company.setUseMinePaotui(true);
                    }
                    if (null != driverChoseLevelFreight) {
                        company.setUseMineFreight(true);
                    }
                }
                mv.addObject("companys", companys);
                mv.addObject("companyId", principal.getCompanyId());

                String detailedJobType = local.getDetailedJobType();
                if (detailedJobType != null) {
                    String[] str = local.getDetailedJobType().split(",");
                    mv.addObject("driverJobTypes", Arrays.asList(str));
                }

                ServiceSetting serviceSetting = ServiceUtil.checkOpen();
                mv.addObject("driver", local);
                if (serviceSetting.isPaotui()) {
                    mv.addObject("detailedJobType",
                        errandService.queryOrderType(local.getCompanyId()));
                }
                if (serviceSetting.isZhuanche()) {
                    if (null != local.getCarId()) {
                        mv.addObject("car", zhuancheService.findCar(local.getCarId()));
                    }
                }
                if (serviceSetting.isFreight()) {
                    if (null != local.getTruckId()) {
                        mv.addObject("truck", freightService.findTruck(local.getTruckId()));
                    }
                }
                if (serviceSetting.isZhuanxian()) {
                    if (null != local.getZhuanxianCarId()) {
                        mv.addObject(CommonCons.ZHUAN_XIAN_CAR,
                            zhuanxianService.findCar(local.getZhuanxianCarId()));
                    }
                    // 城际专线路线、提成
                    Map<String, Long> driverLevelData = new HashMap<>();
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian1 = driverChoseLevelZhuanxianService
                        .findByDriverAndLine(local.getId(), null,
                            DriverChoseLevelZhuanxian.TYPE_PINCHE);
                    if (null != driverChoseLevelZhuanxian1) {
                        driverLevelData.put(CommonCons.DRIVER_LEVEL_ID,
                            driverChoseLevelZhuanxian1.getDriverlevelId());
                    }
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian2 = driverChoseLevelZhuanxianService
                        .findByDriverAndLine(local.getId(), null,
                            DriverChoseLevelZhuanxian.TYPE_BAOCHE);
                    if (null != driverChoseLevelZhuanxian2) {
                        driverLevelData.put(CommonCons.DRIVER_LEVEL_BAOCHE_ID,
                            driverChoseLevelZhuanxian2.getDriverlevelId());
                    }
                    DriverChoseLevelZhuanxian driverChoseLevelZhuanxian3 = driverChoseLevelZhuanxianService
                        .findByDriverAndLine(local.getId(), null,
                            DriverChoseLevelZhuanxian.TYPE_JIHUO);
                    if (null != driverChoseLevelZhuanxian3) {
                        driverLevelData.put(CommonCons.DRIVER_LEVEL_JIHUO_ID,
                            driverChoseLevelZhuanxian3.getDriverlevelId());
                    }
                    mv.addObject(CommonCons.DRIVER_LEVEL_DATA, driverLevelData);
                }
                // 二维码
                Setting setting = settingUtils.get();
                String bathPath = getBasePath(req);
                Company driverCompany = companyService.findOne(local.getCompanyId());
                String qrLogo = driverCompany.getLogo();
                File logof = null;
                if (StringUtils.isNotBlank(qrLogo)) {
                    logof = new File(bathPath, qrLogo);
                }

                String srcLogo = null;

                if (null != logof && logof.exists()) {
                    srcLogo = logof.getAbsolutePath();
                }
                String weixinShareCodeUrl = defaultDriverRebateService.getWeixinShareCodeUrl(local);

                if (weixinShareCodeUrl != null) {
                    SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
                    Date now = new Date();
                    String monthstr = monthFormat.format(now);
                    String filestr = "qrcode/driver/" + monthstr + "/" + now.getTime() + ".jpg";

                    File f = new File(bathPath, filestr);
                    if (!f.getParentFile().exists()) {
                        f.getParentFile().mkdirs();
                    }
                    QRCodeUtil.encode(weixinShareCodeUrl, 500,
                        500, srcLogo, bathPath + "/" + filestr);
                    mv.addObject("shareQrCode", setting.getWebUrl() + "/" + filestr);
                }
                mv.addObject("driverGrades", driverGradeService.findAll());

                if (serviceSetting.isJgpt()) {
                    mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
                } else {
                    mv.addObject("isUpPlatformInfo", false);
                }

                //服务人员推荐提成比例
                DriverRebate rebate = driverRebateService.findByDriverId(id);
                BigDecimal commission1 = null;
                if (null != rebate) {
                    commission1 = rebate.getCommission1();
                }
                mv.addObject("driverRabate", null == commission1 ? 0 : commission1.doubleValue());
                mv.setViewName("driver/edit");

                return mv;
            } else {
                throw new NoPermissionException();
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public @ResponseBody
    Result<Driver> update(Driver driver, Long carId, Long truckId,
        String carNumber, String truckNumber, Long zhuanxianCarId, String zhuanxianNumber,
        HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Driver> result = new Result<Driver>();
        result.setSuccess(false);

        if (subject.isPermitted("driveredit")) {
            Driver local = driverService.findOne(driver.getId());
            if (idCardExists(driver.getIdCard(), driver.getId())) {
                result.setMessage("身份证'" + driver.getIdCard() + "'已存在");
                return result;
            }
            if (phoneExists(driver.getPhone(), driver.getId())) {
                result.setMessage("手机号'" + driver.getPhone() + "'已存在");
                return result;
            }
            String driverRabate = req.getParameter("driverRabate");
            if (!RegExpValidatorUtils.isNumberWithPoint(driverRabate)) {
                System.out.println("参数错误一");
                result.setSuccess(false);
                result.setMessage("参数错误");
                return result;
            }
            BigDecimal commission1 = new BigDecimal(driverRabate);
            if (commission1.compareTo(BigDecimal.ZERO) < 0 || commission1.compareTo(HUNDRED) > 0) {
                System.out.println("参数错误二");
                result.setSuccess(false);
                result.setMessage("参数错误");
                return result;
            }
            Integer tixian = Integer.valueOf(req.getParameter("tixian"));
            local.setTixian(tixian);
            Integer tuiguang = Integer.valueOf(req.getParameter("tuiguang"));
            local.setTuiguang(tuiguang);
            local.setGradeId(driver.getGradeId());
            local.setPhoto(driver.getPhoto());
            local.setLicense(driver.getLicense());
            local.setTravel(driver.getTravel());
            local.setBigPhoto(driver.getBigPhoto());
            local.setIdCardPhoto(driver.getIdCardPhoto());
            local.setIdCardHandPhoto(driver.getIdCardHandPhoto());
            //资格证书
            local.setQualificationPhoto(driver.getQualificationPhoto());
            //身份证反面
            local.setBackOfIdCardPhoto(driver.getBackOfIdCardPhoto());

            local.setName(driver.getName());
            local.setRealname(driver.getRealname());
            local.setNamePinyin(toPinyin(driver.getRealname()));
            local.setGender(driver.getGender());
            local.setType(driver.getType());
            local.setIdCard(driver.getIdCard());
            local.setBankCard(driver.getBankCard());
            local.setPhone(driver.getPhone());
            local.setAddress(driver.getAddress());
            local.setPressingName(driver.getPressingName());
            local.setPressingPhone(driver.getPressingPhone());
            local.setLicenseTime(driver.getLicenseTime());
            local.setLicenseType(driver.getLicenseType());
            local.setIntroducer(driver.getIntroducer());
            local.setHeight(driver.getHeight());
            local.setOrigin(driver.getOrigin());
            local.setMemo(driver.getMemo());
            local.setDriveTimes(driver.getDriveTimes());
            local.setStarLevel(driver.getStarLevel());
            local.setJobTime(driver.getJobTime());
            local.setDriverChoseLevels(driver.getDriverChoseLevels());
            local.setDriverChoseLevelCars(driver.getDriverChoseLevelCars());
            local.setDriverChoseLevelPaotuis(driver.getDriverChoseLevelPaotuis());
            local.setDriverChoseLevelFreights(driver.getDriverChoseLevelFreights());
            local.setDriverChoseLevelZhuanxians(driver.getDriverChoseLevelZhuanxians());

            local.setDetailedJobType(driver.getDetailedJobType());
            local.setErrandserviceType(driver.getErrandserviceType());
            local.setPlatNo(driver.getPlatNo());
            local.setEmergency(driver.getEmergency());
            local.setCarId(carId);

            /**
             * 上传监管平台增加信息
             */
            local.setDriverCensus(driver.getDriverCensus());
            local.setAddressCode(driver.getAddressCode());
            local.setAddressCodeArr(driver.getAddressCodeArr());
            local.setCommercialType(driver.getCommercialType());
            /**
             * 专车新加.
             */
            local.setDriverLicenseNo(driver.getDriverLicenseNo());
            local.setDriverLicenseId(driver.getDriverLicenseId());
            local.setNationality(driver.getNationality());
            local.setBirthday(driver.getBirthday());
            local.setDriverLicenseValid(driver.getDriverLicenseValid());
            local.setDriverLicenseInvalid(driver.getDriverLicenseInvalid());
            local.setTaxiLicenseNo(driver.getTaxiLicenseNo());
            local.setNation(driver.getNation());
            local.setMarital(driver.getMarital());
            local.setForeignLanguageAbility(driver.getForeignLanguageAbility());
            local.setConcatAddress(driver.getConcatAddress());
            local.setEducation(driver.getEducation());
            local.setTaxiLicenseRecive(driver.getTaxiLicenseRecive());
            local.setTaxiLicenseRegister(driver.getTaxiLicenseRegister());
            local.setTaxiLicenseValid(driver.getTaxiLicenseValid());
            local.setTaxiLicenseInvalid(driver.getTaxiLicenseInvalid());
            local.setTaxiLicenseOrg(driver.getTaxiLicenseOrg());
            local.setTrafficViolation(driver.getTrafficViolation());
            local.setContractCompany(driver.getContractCompany());
            local.setContractValid(driver.getContractValid());
            local.setContractInvalid(driver.getContractInvalid());
            local.setCruise(driver.getCruise());
            local.setInBlacklist(driver.getInBlacklist());
            local.setPhoneOperator(driver.getPhoneOperator());
            local.setMapType(driver.getMapType());
            local.setEmergencyAddress(driver.getEmergencyAddress());
            local.setSeviceReview(driver.getSeviceReview());

            boolean driverJobTypeChange = false;// 服务人员工作类型是否改变
            if (!local.getDriverJobType().equals(driver.getDriverJobType())) {
                driverJobTypeChange = true;
            }
            local.setDriverJobType(driver.getDriverJobType());
            if (carId != null) {
                if (StringUtils.isNotBlank(carNumber)) {
                    zhuancheService.updateCar(carId, null, null, null, null, null, null, null, null,
                        local.getId(), local.getUsername() + " " + local.getPhone(), null, null,
                        null);
                } else {
                    zhuancheService.updateCar(carId, null, null, null, null, null, null, null, null,
                        local.getId(), "", null, null, null);
                }
            }
            if (StringUtils.isNotBlank(truckNumber)) {
                Driver oldDriver = driverMapper.selectByTruckId(truckId);
                if (null != oldDriver && !oldDriver.getId().equals(local.getId())) {
                    oldDriver.setTruckId(null);

                    driverService.updateByPrimaryKey(oldDriver);
                    local.setTruckId(truckId);
                    freightService.updateTruck(truckId, null, null, null, null, null, null, null,
                        local.getId(), local.getRealname() + "  " + local.getPhone());
                } else {
                    local.setTruckId(truckId);
                    freightService.updateTruck(truckId, null, null, null, null, null, null, null,
                        local.getId(), local.getRealname() + "  " + local.getPhone());
                }
            }

            if (StringUtils.isNotBlank(zhuanxianNumber)) {
                Driver oldDriver = driverMapper.selectByZhuanxianCarId(zhuanxianCarId);
                if (null != oldDriver && !oldDriver.getId().equals(local.getId())) {
                    oldDriver.setZhuanxianCarId(null);
                    driverService.updateByPrimaryKey(oldDriver);
                    local.setZhuanxianCarId(zhuanxianCarId);
                    zhuanxianService.updateCar(zhuanxianCarId, null, null, null, null, null, null,
                        local.getId(), local.getRealname() + "  " + local.getPhone(), null);
                } else {
                    local.setZhuanxianCarId(zhuanxianCarId);
                    zhuanxianService.updateCar(zhuanxianCarId, null, null, null, null, null, null,
                        local.getId(), local.getRealname() + "  " + local.getPhone(), null);
                }
            }

            String basePath = getBasePath(req);
            driverService.updateInfo(local, basePath, carNumber);

            String detail = "【%s】修改了服务人员【" + local.getUsername() + "(" + local.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            if (driverJobTypeChange) {// 如果服务人员工作类型改变
                DriverJobTypeChangeEvent settingChangeEvent = new DriverJobTypeChangeEvent(local);
                applicationEventMulticaster.multicastEvent(settingChangeEvent);
            }

            //服务人员推荐提成
            if (StringUtils.isNotBlank(driverRabate)) {
                DriverRebate byDriverId = driverRebateService.findByDriverId(driver.getId());
                if (null != byDriverId) {
                    byDriverId.setCommission1(commission1);
                    byDriverId.setUpdated(new Date());
                    driverRebateService.update(byDriverId);
                } else {
                    byDriverId = new DriverRebate();
                    byDriverId.setCommission1(commission1);
                    byDriverId.setDriverId(driver.getId());
                    byDriverId.setType(DriverRebate.FIX_TYPR);
                    byDriverId.setLevel(DriverRebate.FIX_LEVEL);
                    byDriverId.setDriverRebateType1(DriverRebate.DriverRebateType.percent);
                    byDriverId.setCreated(new Date());
                    driverRebateService.save(byDriverId);
                }
            }
            result.setSuccess(true);
            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "getCar", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getCar(String carNumber) {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        List<Car> carList = zhuancheService.findCarsByNumber(carNumber, principal.getCompanyId());

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        for (Car car : carList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", car.getId());
            map.put("name", car.getCarName());
            map.put("carNumber", car.getCarNumber());
            map.put("flights", car.getFlights());
            map.put("employId", car.getEmployId());
            list.add(map);
        }

        return list;
    }

    @RequestMapping(value = "getTruck", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getTruck(String carNumber) {

        List<Truck> truckList = freightService.findTruckByNumber(carNumber);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Truck truck : truckList) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", truck.getId());
            map.put("name", truck.getTruckTypeName());
            map.put("cangointotown", truck.getCangointotown());
            map.put("carNumber", truck.getCarNumber());
            map.put("employId", truck.getDriverId());
            list.add(map);
        }
        return list;
    }

    @RequestMapping(value = "getZhuanxianCar", method = RequestMethod.GET)
    public @ResponseBody
    List<com.ybkj.daijia.server.zhuanxian.Car> getZhuanxianCar(
        String carNumber) {

        List<com.ybkj.daijia.server.zhuanxian.Car> carList = zhuanxianService
            .findCarByNumber(carNumber);

        return carList;
    }


    @RequestMapping(value = "money/{id}", method = RequestMethod.GET)
    public ModelAndView money(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("drivermoneyview")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/money");

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());
            BigDecimal helppayMoney = helppayService.getHelppayMoneyById(id);
            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isEmpty(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isEmpty(startTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.MONTH, -1);
                    start = cl.getTime();
                } else {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
            mv.addObject("helppayMoney", helppayMoney != null ? helppayMoney.doubleValue() : 0);
            mv.addObject("start", start);
            mv.addObject("end", end);
            mv.addObject("driver", driverService.findOne(id));
            Page page = driverPaymentsRecordService
                .queryByEmply2(id, null, null, start, end, Pager.getPage(), Pager.getLimit());
            mv.addObject("page", page);

            List<DriverPaymentsRecord> list = driverPaymentsRecordService
                .listIndexPayments(id, start, end);
            BigDecimal bd = BigDecimal.ZERO;
            for (DriverPaymentsRecord dp : list) {
                BigDecimal moeny = dp.getMoney();
                Integer rcType = dp.getRcType();
                String recordType = dp.getRecordType();
                // 订单产值
                if (rcType == 0 && DriverPaymentsRecord.RECHARGE_TYPE_ORDER.equals(recordType)) {
                    bd = bd.add(moeny);
                }
            }
            bd = bd.setScale(2);
            mv.addObject("allPayments", bd);
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /***
     * 服务人员充值
     * @param driverPaymentsRecord
     * @param driverid
     * @return
     */
    @RequestMapping(value = "money", method = RequestMethod.POST)
    public synchronized String money(DriverPaymentsRecord driverPaymentsRecord, Long driverid) {
        //$$$服务人员充值
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("drivermoney")) {
            BigDecimal money = driverPaymentsRecord.getMoney();
            BigDecimal helppay = driverPaymentsRecord.getHelppay();
            if (null != money) {
                if (money.compareTo(BigDecimal.ZERO) != 0) {
                    //余额金额操作
                    String memo =
                        principal.getUsername() + "[" + principal.getId() + "]为司机[" + driverid
                            + "] 充值余额" + money + "元";
                    driverService.money(driverid, driverPaymentsRecord, memo);

                    Driver driver = driverService.findOne(driverid);

                    String detail =
                        "【%s】为服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】充值"
                            + money + "，备注：" + driverPaymentsRecord.getMemo();
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    ReactorVo rVo = new ReactorVo();
                    rVo.setDriver(driver);
                    rVo.setMoney(money);
                    rVo.setType("admin");
                    DriverRechargeEvent rechargeEvent = new DriverRechargeEvent(rVo);
                    applicationEventMulticaster.multicastEvent(rechargeEvent);

                    Setting setting = settingUtils.get();
                    if (driver.getStatus().equals(Driver.DRIVER_ONLINE)
                        && driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
                        && setting.getLowestWorkVirtual() != 0
                        && driver.getVirtual().doubleValue() < setting.getLowestWorkVirtual()) {

                        driver.setStatus(Driver.DRIVER_OFFLINE);
                        driverService.updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

                        DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(
                            driver,
                            Driver.DRIVER_ONLINE, "sys");
                        applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);
                    }

                }
            }
            if (null != helppay) {
                if (0 != helppay.compareTo(BigDecimal.ZERO)) {
                    //代付金额操作
                    HelpPayRecord helpPayRecord = new HelpPayRecord();
                    //需要在driverService操作前先setmoney,否则负数都会变成正数
                    helpPayRecord.setChangeMoney(helppay);
                    helpPayRecord.setDriverId(driverid);
                    //helpPayRecord.setPaymentRecordId(driverPaymentsRecord.getId());
                    //小于零，扣款
                    if (0 > helppay.compareTo(BigDecimal.ZERO)) {
                        helpPayRecord.setOperateType(HelpPayRecord.SINGE_SUB);
                    }
                    //大于零，充值
                    if (0 < helppay.compareTo(BigDecimal.ZERO)) {
                        helpPayRecord.setOperateType(HelpPayRecord.SINGE_RECHARGE);
                    }

                    helpPayRecord.setMemo(
                        principal.getUsername() + "[" + principal.getId() + "]为司机[" + driverid
                            + "] 充值代付金额" + helppay + "元");
                    helppayService.operateDriverMoney(helpPayRecord);

                    Driver driver = driverService.findOne(driverid);

                    String detail =
                        "【%s】为服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】充值"
                            + helppay + "，备注：" + driverPaymentsRecord.getMemo();
                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    ReactorVo rVo = new ReactorVo();
                    rVo.setDriver(driver);
                    rVo.setMoney(helppay);
                    rVo.setType("admin");
                    DriverRechargeEvent rechargeEvent = new DriverRechargeEvent(rVo);
                    applicationEventMulticaster.multicastEvent(rechargeEvent);

                    Setting setting = settingUtils.get();
                    if (driver.getStatus().equals(Driver.DRIVER_ONLINE)
                        && driver.getType().equals(Driver.DRIVER_TYPR_PARTTIME)
                        && setting.getLowestWorkVirtual() != 0
                        && driver.getVirtual().doubleValue() < setting.getLowestWorkVirtual()) {

                        driver.setStatus(Driver.DRIVER_OFFLINE);
                        driverService.updateStatus(Driver.DRIVER_OFFLINE, driver.getId());

                        DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(
                            driver, Driver.DRIVER_ONLINE, "sys");
                        applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);
                    }
                }
            }

            return "redirect:money/" + driverid;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "paymentsExport/{id}", method = RequestMethod.GET)
    public void paymentsExport(@PathVariable("id") Long id, HttpServletRequest req,
        HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("drivermoney")) {

            List<DriverPaymentsRecord> list = driverPaymentsRecordService
                .listByEmploy(id, null, null,
                    null, null);

            String[] heards = {"时间", "订单号", "金额(元)", "操作后余额(元)", "充值/消费方式", "操作人", "备注"};

            List<List<String>> rowlist = new ArrayList<List<String>>();

            SimpleDateFormat formatter = com.ybkj.daijia.constant.DateConstant.DATE_TIME;

            for (DriverPaymentsRecord c : list) {

                List<String> celllist = new ArrayList<String>();

                celllist.add(formatter.format(c.getHappend()));

                celllist.add(c.getOrderNumber());

                if (c.getRcType().equals(DriverPaymentsRecord.DIFFERENT_NEGATIVE)) {
                    celllist.add("-" + c.getMoney().toString());
                } else {
                    celllist.add(c.getMoney().toString());
                }

                celllist.add(c.getAfterMoney().toString());

                celllist.add(c.getRecordTypeStr());

                celllist.add(c.getOperating());

                celllist.add(c.getMemo());

                rowlist.add(celllist);
            }

            ExcelUtil.export(req, response, heards, rowlist);

        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "inandout/{id}", method = RequestMethod.GET)
    public ModelAndView inandout(@PathVariable("id") Long id,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) throws ParseException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());

            Date start = null;
            Date end = null;
            if (StringUtils.isEmpty(endTime)) {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                cl.add(Calendar.HOUR_OF_DAY, 23);
                cl.add(Calendar.MINUTE, 59);
                cl.add(Calendar.SECOND, 59);
                end = cl.getTime();
            } else {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                cl.add(Calendar.HOUR_OF_DAY, 23);
                cl.add(Calendar.MINUTE, 59);
                cl.add(Calendar.SECOND, 59);
                end = cl.getTime();
            }

            if (StringUtils.isEmpty(startTime)) {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                cl.add(Calendar.MONTH, -1);
                start = cl.getTime();
            } else {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
            }

            ModelAndView mv = new ModelAndView();
            mv.setViewName("driver/inandout");
            mv.addObject("driver", driverService.findOne(id));

            mv.addObject("page",
                driverPaymentsRecordService.queryByEmploy(id, null, null, start, end,
                    Pager.getPage(), Pager.getLimit()));

            mv.addObject("start", start);
            mv.addObject("end", end);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "inandoutExport/{id}", method = RequestMethod.GET)
    public void inandoutExport(@PathVariable("id") Long id, HttpServletRequest req,
        HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {

            // 充值记录
            List<DriverPaymentsRecord> list = driverPaymentsRecordService
                .listByEmploy(id, null, null,
                    null, null);

            String[] heards = {"时间", "金额(元)", "操作后余额(元)", "类型", "操作人", "备注"};

            List<List<String>> rowlist = new ArrayList<List<String>>();

            DateFormat format = com.ybkj.daijia.constant.DateConstant.DATE_TIME;

            for (DriverPaymentsRecord c : list) {

                List<String> celllist = new ArrayList<String>();

                celllist.add(format.format(c.getHappend()));

                celllist.add(c.getMoney().toString());

                celllist.add(c.getAfterMoney().toString());

                celllist.add(c.getRecordTypeStr());

                celllist.add(c.getOperating());

                celllist.add(c.getMemo());

                rowlist.add(celllist);
            }

            ExcelUtil.export(req, response, heards, rowlist);

        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "diaodu/mapmode", method = RequestMethod.GET)
    public ModelAndView mapmode() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("dispatch")) {
            ModelAndView mv = new ModelAndView();

            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();

            Company company = companyService.findOne(principal.getCompanyId());

            mv.addObject("longitude", company.getLongitude());
            mv.addObject("latitude", company.getLatitude());

            mv.addObject("newOrders", orderService.listNewOrders(9));

            mv.setViewName("diaodu/mapmode");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "diaodu/mapmodeData", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> mapmodeData() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("dispatch")) {

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("newOrders", orderService.listNewOrders(9));

            return map;

        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "diaodu/listmode", method = RequestMethod.GET)
    public ModelAndView listmode() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("paidan")) {
            ModelAndView mv = new ModelAndView();

            List<Driver> drivers = driverService.listmodeDrivers();

            Order lastOne = orderService.findOneYestodayOrder();

            if (lastOne == null) {
                lastOne = new Order();
            }

            if (!CollectionUtils.isEmpty(drivers)) {
                for (Driver driver : drivers) {
                    Order order = orderService
                        .findOneByDriverBeforeComplete(driver.getId(), lastOne.getId());

                    if (null == order) {
                        order = orderService
                            .findOneByDiverAndFinish(driver.getId(), lastOne.getId());
                    }
                    driver.setDiaoduOrder(order);

                    long yupai = orderService.countByDriverAndStatus(driver.getId(),
                        Order.ORDER_STATUS_YUPAIDAN, lastOne.getId());
                    driver.setYupai(yupai);
                }
            }

            mv.addObject("drivers", drivers);

            mv.addObject("newOrders", orderService.listNewOrders(50));

            mv.setViewName("diaodu/listmode");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "diaodu/findDriverDetail", method = RequestMethod.POST)
    public @ResponseBody
    Result<Driver> findDriverDetail(Long driverID) {

        Result<Driver> result = new Result<Driver>();

        Driver driver = driverService.findOne(driverID);

        Order lastOne = orderService.findOneYestodayOrder();

        if (lastOne == null) {
            lastOne = new Order();
        }

        if (null != driver) {

            Order order = orderService
                .findOneByDiverAndStatus(driver.getId(), Order.ORDER_STATUS_BUSY);
            if (null == order) {
                order = orderService
                    .findOneByDiverAndStatus(driver.getId(), Order.ORDER_STATUS_YIPAIDAN);
            }
            if (null == order) {
                order = orderService.findOneByDiverAndFinish(driver.getId(), lastOne.getId());
            }
            driver.setDiaoduOrder(order);

            long yupai = orderService
                .countByDriverAndStatus(driver.getId(), Order.ORDER_STATUS_YUPAIDAN,
                    lastOne.getId());
            driver.setYupai(yupai);

        }

        result.setObject(driver);
        result.setSuccess(null != driver);

        return result;
    }

    @RequestMapping(value = "findDriver", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> findDriver(String keyword) {

        List<Driver> drivers = new ArrayList<Driver>();
        if (StringUtils.isNotBlank(keyword)) {
            drivers = driverService.findDriver(keyword);
        }

        return drivers;
    }

    @RequestMapping(value = "diaodu/listmode2", method = RequestMethod.GET)
    public ModelAndView listmode2() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("paidan")) {
            ModelAndView mv = new ModelAndView();

            List<Driver> drivers = driverService.listmodeDrivers();
            if (!CollectionUtils.isEmpty(drivers)) {
                for (Driver driver : drivers) {
                    List<Order> workingOrders = orderService
                        .listWorkingOrdersByDriver(driver.getId());
                    List<Order> yupaidanOrders = orderService.listByDriverAndStatus(driver.getId(),
                        Order.ORDER_STATUS_YUPAIDAN);
                    driver.setWorkingOrders(workingOrders);
                    driver.setYupaidanOrders(yupaidanOrders);
                }
            }
            mv.addObject("drivers", drivers);

            mv.addObject("newOrders", orderService.listNewOrders(50));

            mv.setViewName("diaodu/listmode");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    // 预派单 推荐服务人员
    @RequestMapping(value = "tuijianDrivers", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> tuijianDrivers(Long orderid) {

        Setting oldsetting = settingUtils.get();
        Double paidanKm = oldsetting.getPaidanKm();

        Order order = orderService.findOne(orderid);
        Double orderlng = order.getClientLongitude();
        Double orderlat = order.getClientLatitude();

        // 附近服务人员
        List<Driver> drivers = driverService.queryPaidanTuijian(orderlng, orderlat, paidanKm);
        if (CollectionUtils.isEmpty(drivers)) {
            drivers = new LinkedList<Driver>();
        }

        // 查询在执行中的已完成时间在 半小时内的，目的地与新单相同的单 服务人员
        List<Order> orders = orderService.queryNearBy(orderlng, orderlat, paidanKm);
        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order2 : orders) {
                if (null != order2.getDriverId()) {
                    Driver driver = driverService.findOne(order2.getDriverId());
                    Date arriveTime = HttpClientUtil.getDateByTwoPoints(driver.getLongitude(),
                        driver.getLatitude(), order2.getToPlaceLongitude(),
                        order2.getToPlaceLatitude());

                    Long time = (order.getServerTime().getTime() - arriveTime.getTime()) / (1000
                        * 60); // 预约时间
                    // -
                    // 到达时间

                    if (null != arriveTime && time >= 0 && time <= 60) {
                        drivers.add(driver);
                    }
                }
            }
        }

        if (CollectionUtils.isEmpty(drivers)) {
            drivers = driverService.queryPaidanTuijian(orderlng, orderlat, 40d);
        }
        if (CollectionUtils.isEmpty(drivers)) {
            drivers = new LinkedList<Driver>();
        }

        if (!CollectionUtils.isEmpty(drivers)) {
            // 计算距离
            DecimalFormat df = new DecimalFormat("#.00");
            for (Driver driver : drivers) {
                driver.setCompany(companyService.findOne(driver.getCompanyId()));
                double distance = Distance.doubleVal(orderlat, orderlng, driver.getLatitude(),
                    driver.getLongitude());
                driver.setDistance(distance);
                if (distance >= 1) {
                    driver.setDistanceStr(df.format(distance) + "公里");
                } else {
                    driver.setDistanceStr((long) (distance * 1000) + "米");
                }
            }

            Collections.sort(drivers, new Comparator<Driver>() {
                public int compare(Driver arg0, Driver arg1) {
                    return arg0.getDistance().compareTo(arg1.getDistance());
                }
            });
        }

        return drivers;

    }

    // 返回服务人员位置和到达目的地时间
    @RequestMapping(value = "listmodeInitialise", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, String> listmodeInitialise(Double driverlng, Double driverlat,
        Double toplacelng, Double toplacelat) {

        Map<String, String> map = new HashMap<String, String>();
        if (null == driverlng || null == driverlat) {
            return map;
        }

        String position = HttpClientUtil.getPlaceByLngAndLat(driverlng, driverlat);
        if (StringUtils.isNoneBlank(position)) {
            position = position.replaceAll("^.*?省", "").replaceAll("^.*?市", "")
                .replaceAll("^.*?区", "");
            map.put("position", position);
        }

        if (null != toplacelng && null != toplacelat) {
            String timestr = HttpClientUtil.getHaMTimeByTwoPoints(driverlng, driverlat, toplacelng,
                toplacelat);
            if (StringUtils.isNoneBlank(timestr)) {
                map.put("timestr", timestr);
            }
        }

        return map;

    }

    // 列出订单附近服务人员
    @RequestMapping(value = "listdistance", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> listdistance(Double longitude, Double latitude,
        OrderCarType orderCarType) {

        String driverJobType = Driver.DriverJobType.daijia.toString();

        if (null != longitude && null != latitude) {
            return driverService.listdistance(longitude, latitude, driverJobType);
        }
        return new ArrayList<Driver>();

    }

    // 列出调度推荐服务人员
    @RequestMapping(value = "listdiaodutuijian", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> listdiaodutuijian(Double longitude, Double latitude,
        Long orderId) {

        if (null != longitude && null != latitude && null != orderId) {
            return driverService.listdiaodutuijian(longitude, latitude, orderId);
        }
        return new ArrayList<Driver>();

    }

    // 根据昵称,工号,电话模糊查询服务人员
    @RequestMapping(value = "getDriver", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getDriver(String param) {
        List<Driver> drivers = driverService.findByParamLike(param, null);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Driver driver : drivers) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", driver.getId());
            map.put("username", driver.getUsername());// 工号
            map.put("name", driver.getName());// 昵称
            map.put("realname", driver.getRealname());
            map.put("phone", driver.getPhone());// 电话
            list.add(map);
        }
        return list;

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest request) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driverdelete")) {
            Result<Integer> result = new Result<Integer>();
            Driver driver = driverService.findOne(id);

            String detail =
                "【%s】删除了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";

            driverService.delete(driver, getBasePath(request));

            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteRecord", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> deleteRecord(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driver")) {
            Result<Integer> result = new Result<Integer>();
            PhoneRecord phoneRecord = phoneRecordService.findOne(id);

            SimpleDateFormat formatter = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
            String phoneDate = formatter.format(phoneRecord.getPhoneDate());
            String hasOrder = "无";
            if (phoneRecord.isHasOrders()) {
                hasOrder = "有";
            }

            String detail = "【%s】删除了通话记录，服务人员【" + phoneRecord.getDriverPhone() + "("
                + phoneRecord.getDriverName() + "】" + "，对方号码：" + phoneRecord.getMemberPhone() + ""
                + "，通话时间：" + phoneDate + "" + "，通话时长：" + phoneRecord.getPhoneTime() + "秒"
                + "，30分钟内："
                + hasOrder + "订单";

            phoneRecordService.delete(phoneRecord);

            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteRecords", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> deleteRecords(Long[] ids) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driver")) {
            Result<Integer> result = new Result<Integer>();

            List<String> strlist = new ArrayList<String>();
            for (Long rid : ids) {
                PhoneRecord phoneRecord = phoneRecordService.findOne(rid);
                SimpleDateFormat formatter = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
                String phoneDate = formatter.format(phoneRecord.getPhoneDate());
                String hasOrder = "无";
                if (phoneRecord.isHasOrders()) {
                    hasOrder = "有";
                }

                String detail = "【%s】删除了通话记录，服务人员【" + phoneRecord.getDriverPhone() + "("
                    + phoneRecord.getDriverName() + "】" + "，对方号码：" + phoneRecord.getMemberPhone()
                    + ""
                    + "，通话时间：" + phoneDate + "" + "，通话时长：" + phoneRecord.getPhoneTime() + "秒"
                    + "，30分钟内："
                    + hasOrder + "订单";
                strlist.add(detail);
            }

            phoneRecordService.delete(ids);

            for (String detail : strlist) {
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);
            }

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "dongjie", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> dongjie(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driveredit")) {
            Result<Integer> result = new Result<Integer>();

            Driver driver = driverService.findOne(id);
            driver.setIsFreeze(true);
            driverService.updateByPrimaryKey(driver);

            Integer oldstatus = driver.getStatus();

            driverService.poweroffline(id);

            String detail =
                "【%s】冻结了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(driver,
                oldstatus, "admin");
            applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "jiedong", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> jiedong(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driveredit")) {
            Result<Integer> result = new Result<Integer>();
            Driver driver = driverService.findOne(id);
            driver.setIsFreeze(false);
            driverService.updateByPrimaryKey(driver);

            DriverLogin driverLogin = driverLoginService.selectByDriver(driver.getId());
            if (null != driverLogin) {
                Calendar calendar = Calendar.getInstance();
                driverLogin.setRefreshDate(calendar.getTime());
                calendar.add(Calendar.MINUTE, DriverLogin.VALID_TIME);
                driverLogin.setDeathDate(calendar.getTime());
                driverLoginService.update(driverLogin);
            }

            result.setSuccess(true);

            String detail =
                "【%s】解冻了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "jiebang", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> jiebang(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driveredit")) {

            Result<Integer> result = new Result<Integer>();

            Driver driver = driverService.findOne(id);

            Integer oldstatus = driver.getStatus();

            DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(driver,
                oldstatus, "admin");
            applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);

            driverService.jiebang(id);
            DriverLogin driverLogin = driverLoginService.selectByDriver(id);
            if (null != driverLogin) {
                Calendar calendar = Calendar.getInstance();
                driverLogin.setDeathDate(calendar.getTime());
                driverLoginService.update(driverLogin);
            }

            String detail =
                "【%s】解绑了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "poweroffline", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> poweroffline(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Integer> result = new Result<Integer>();

        if (subject.isPermitted("driveredit")) {

            Driver driver = driverService.findOne(id);

            Integer oldstatus = driver.getStatus();

            driverService.poweroffline(id);

            DriverPowerOfflineEvent driverPowerOfflineEvent = new DriverPowerOfflineEvent(driver,
                oldstatus, "admin");
            applicationEventMulticaster.multicastEvent(driverPowerOfflineEvent);

            String detail =
                "【%s】强制下线了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);

            return result;
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "online", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> online(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Integer> result = new Result<Integer>();

        if (subject.isPermitted("driveredit")) {
            Driver driver = driverService.findOne(id);

            if (driver.getStatus().equals(Driver.DRIVER_OFFLINE)) {
                driverService.online(driver);
                result.setSuccess(true);

                String detail =
                    "【%s】上线了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                return result;
            }

            result.setSuccess(false);
            result.setMessage("只有离线服务人员才能上线");
            return result;

        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "getGtStatus", method = RequestMethod.POST)
    public @ResponseBody
    Result<String> getGtStatus(String userid) {

        Subject subject = SecurityUtils.getSubject();
        Result<String> result = new Result<String>();

        if (subject.isPermitted("driver")) {
            try {
                String clientStatus = GeTuiEmployV4.getClientStatus(userid, settingUtils.get());
                String clientStatusGeneral = GeTuiEmployV4
                    .getClientStatusGeneral(userid, settingUtils.get());
                if ("Online".equals(clientStatus)) {
                    result.setResult(clientStatus);
                } else {
                    result.setResult(clientStatusGeneral);
                }
                result.setSuccess(true);
                return result;
            } catch (IOException e) {
                result.setSuccess(false);
                result.setMessage("获取失败");
                return result;
            }
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    /*
     * 获取在线状态
     */
    @RequestMapping(value = "diaodu/mapmodeDatav3", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> mapmodeDatav3(boolean loadLixian) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("dispatch")) {
            Long companyId = principal.getCompanyId();
            //查询所有线路
            List<Line> lineList = zhuanxianService.queryLines(companyId);
//            for (Line line : lineList) {
//                if (subject.isPermitted(line.getId().toString())) {
//                    System.out.println("有权限:" + line.getId());
//                } else {
//                    System.out.println("没有权限" + line.getId());
//                }
//            }
//            System.out.println("------------------------------------");

            Map<String, Object> dataMap = new HashMap<String, Object>();

            DateFormat format = new SimpleDateFormat("HH:mm");

            List<Map<String, Object>> orderMapList = new ArrayList<Map<String, Object>>();

            ServiceSetting serviceSetting = ServiceUtil.checkOpen();

            if (serviceSetting.isDaijia()) {
                // 代驾单
                List<Order> daijiaOrders = orderService.listNewOrders(20);
                if (!CollectionUtils.isEmpty(daijiaOrders)) {
                    for (Order order : daijiaOrders) {
                        Map<String, Object> daijiaMap = new HashMap<String, Object>();
                        daijiaMap.put("type", "daijia");
                        daijiaMap.put("id", order.getId());
                        daijiaMap.put("orderNumber", order.getOrderNumber());
                        daijiaMap.put("fromPlace", order.getFromPlace());
                        daijiaMap.put("toPlace", order.getToPlace());
                        daijiaMap.put("clientLatitude", order.getClientLatitude());
                        daijiaMap.put("clientLongitude", order.getClientLongitude());
                        daijiaMap.put("clientName", order.getClientName());
                        daijiaMap.put("serverTime", format.format(order.getServerTime()));
                        orderMapList.add(daijiaMap);
                    }
                }
            }

            // 专车单
            // 判断是否开启专车开关
            if (serviceSetting.isZhuanche()) {
                if (subject.isPermitted("zhuancheDispatch")) {
                    List<com.ybkj.daijia.server.zhuan.Order> zhuancheOrders = zhuancheService
                        .listNewOrders();
                    if (!CollectionUtils.isEmpty(zhuancheOrders)) {
                        for (com.ybkj.daijia.server.zhuan.Order order : zhuancheOrders) {
                            Map<String, Object> zhuancheMap = new HashMap<String, Object>();
                            zhuancheMap.put("type", "zhuanche");
                            zhuancheMap.put("id", order.getId());
                            zhuancheMap.put("orderNumber", order.getOrderNo());
                            zhuancheMap.put("fromPlace", order.getStartAddress());
                            zhuancheMap.put("toPlace", order.getEndAddress());
                            zhuancheMap.put("clientLatitude", order.getStartLat());
                            zhuancheMap.put("clientLongitude", order.getStartLng());
                            zhuancheMap.put("clientName", order.getPassengerName());
                            zhuancheMap.put("serverTime", format.format(order.getServerTime()));
                            zhuancheMap.put("carTypeName", order.getCarTypeName());
                            orderMapList.add(zhuancheMap);
                        }
                    }
                }
            }

            // 跑腿单
            if (serviceSetting.isPaotui()) {
                List<com.ybkj.daijia.server.errand.OrderUp> errandOrders = null;
                try {
                    errandOrders = errandService.listNewOrders();
                } catch (Exception e) {

                    e.printStackTrace();
                }

                if (!CollectionUtils.isEmpty(errandOrders)) {
                    for (com.ybkj.daijia.server.errand.OrderUp order : errandOrders) {
                        Map<String, Object> errandMap = new HashMap<String, Object>();
                        errandMap.put("type", "errand");
                        errandMap.put("id", order.getId());
                        errandMap.put("orderNumber", order.getOrderNo());
                        errandMap.put("fromPlace", order.getStartAddress());
                        errandMap.put("toPlace", order.getDeliverAddress());
                        errandMap.put("clientLatitude", order.getStartLat());
                        errandMap.put("clientLongitude", order.getStartLng());
                        errandMap.put("clientName", order.getPassengerName());
                        errandMap
                            .put("serverTime", format.format(order.getStartTime() != null ? order
                                .getStartTime() : order.getCreated()));
                        errandMap.put("orderType", order.getOrderType());
                        orderMapList.add(errandMap);
                    }
                }
            }

            // 城际专线
            // 判断是否有城际专线调度权限
            if (subject.isPermitted("zhuanxianDispatch")) {
                // 货运单
                if (serviceSetting.isFreight()) {
                    List<com.ybkj.daijia.server.freight.Order> freightOrders = freightService
                        .listNewOrders();
                    if (!CollectionUtils.isEmpty(freightOrders)) {
                        for (com.ybkj.daijia.server.freight.Order order : freightOrders) {
                            Map<String, Object> freightMap = new HashMap<String, Object>();
                            freightMap.put("type", "freight");
                            freightMap.put("id", order.getId());
                            freightMap.put("orderNumber", order.getOrderNo());
                            freightMap.put("fromPlace", order.getStartAddress());
                            freightMap.put("toPlace", order.getDestination());
                            freightMap.put("clientLatitude", order.getStartLat());
                            freightMap.put("clientLongitude", order.getStartLng());
                            freightMap.put("clientName", order.getPassengerName());
                            freightMap.put("serverTime", format.format(order.getStartTime()));
                            freightMap.put("carTypeName", order.getTruckTypeName()
                                + (order.getTruckType() != null && order.getTruckType()
                                .getCangointotown() ? "--入城" : ""));
                            orderMapList.add(freightMap);
                        }
                    }
                }

                // 专线拼车、包车单
                if (serviceSetting.isZhuanxian()) {
                    List<com.ybkj.daijia.server.zhuanxian.Order> zhuanxianOrders = zhuanxianService
                        .listNewOrders();
                    if (!CollectionUtils.isEmpty(zhuanxianOrders)) {
                        for (com.ybkj.daijia.server.zhuanxian.Order order : zhuanxianOrders) {
                            //获取订单线路id
                            Long lineId = order.getLineId();
                            //如果该账号拥有该线路权限，展示该线路的订单
                            if (subject.isPermitted(lineId.toString())) {
                                Map<String, Object> zhuanxianMap = new HashMap<String, Object>();
                                zhuanxianMap.put("type", "zhuanxian");
                                zhuanxianMap.put("id", order.getId());
                                zhuanxianMap.put("orderNumber", order.getOrderNo());
                                zhuanxianMap.put("fromPlace", order.getStartAddress());
                                zhuanxianMap.put("toPlace", order.getEndAddress());
                                zhuanxianMap.put("clientLatitude", order.getStartLat());
                                zhuanxianMap.put("clientLongitude", order.getStartLng());
                                zhuanxianMap.put("clientName", order.getPassengerName());
                                zhuanxianMap
                                    .put("serverTime", format.format(order.getServerTime()));
                                zhuanxianMap.put("orderType", order.getOrderTypeStr());
                                zhuanxianMap.put("lineName", order.getLineName());
                                zhuanxianMap.put("yuyue", order.isYuyue());
                                zhuanxianMap.put("peopleNumber", order.getPeopleNumber());
                                orderMapList.add(zhuanxianMap);
                            }

                        }
                    }
                }
            }

            // 服务人员
            List<Driver> driverList = driverService.listDiaoduv3(loadLixian);
            if (!CollectionUtils.isEmpty(driverList)) {
                for (Driver driver : driverList) {
                    driver.setCompany(companyService.findOne(driver.getCompanyId()));
                    if (driver.getStatus().equals(Driver.DRIVER_APPLY_ORDER)
                        || driver.getStatus().equals(Driver.DRIVER_BUSY)) {

                        if (Driver.DRIVER_JOBSTATUS_DAIJIA.equals(driver.getJobStatus())) {// 代驾
                            List<Order> daijiaorders = orderService
                                .findActivedOrdersByDriver(driver.getId());
                            if (!CollectionUtils.isEmpty(daijiaorders)) {
                                Order daijiaOrder = daijiaorders.get(0);

                                OrderInfo orderInfo = new OrderInfo();
                                orderInfo.setOrderNumber(daijiaOrder.getOrderNumber());
                                orderInfo.setDate(format.format(daijiaOrder.getServerTime()));
                                orderInfo.setFromPlace(daijiaOrder.getFromPlace());
                                orderInfo.setToPlace(daijiaOrder.getToPlace());
                                orderInfo.setStatus(daijiaOrder.getStatus());
                                if (daijiaOrder.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
                                    if (null != daijiaOrder.getStartDriveDate()) {
                                        orderInfo.setStatus(4);
                                    } else if (null != daijiaOrder.getArrivePlaceDate()) {
                                        orderInfo.setStatus(3);
                                    }
                                }

                                driver.setOrderInfo(orderInfo);
                            }
                        } else if (Driver.DRIVER_JOBSTATUS_ZHUANCHE
                            .equals(driver.getJobStatus())) {// 专车
                            List<com.ybkj.daijia.server.zhuan.Order> zhuancheorders = zhuancheService
                                .findActivedOrdersByDriver(driver.getId());
                            if (!CollectionUtils.isEmpty(zhuancheorders)) {
                                com.ybkj.daijia.server.zhuan.Order zhuancheOrder = zhuancheorders
                                    .get(0);

                                OrderInfo orderInfo = new OrderInfo();
                                orderInfo.setOrderNumber(zhuancheOrder.getOrderNo());
                                orderInfo.setDate(format.format(zhuancheOrder.getServerTime()));
                                orderInfo.setFromPlace(zhuancheOrder.getStartAddress());
                                orderInfo.setToPlace(zhuancheOrder.getEndAddress());
                                orderInfo.setStatus(zhuancheOrder.getStatus());

                                driver.setOrderInfo(orderInfo);
                            }
                        } else if (Driver.DRIVER_JOBSTATUS_PAOTUI
                            .equals(driver.getJobStatus())) {// 跑腿
                            List<com.ybkj.daijia.server.errand.OrderUp> errandorders = errandService
                                .findActivedOrdersByDriver(driver.getId());
                            if (!CollectionUtils.isEmpty(errandorders)) {
                                String jobContent = "";
                                Integer status = null;
                                for (com.ybkj.daijia.server.errand.OrderUp errandorder : errandorders) {
                                    jobContent += errandorder.getContent() + ",";
                                    if (null == status) {
                                        status = errandorder.getStatus();
                                    } else if (errandorder.getStatus() > status) {
                                        status = errandorder.getStatus();
                                    }
                                }

                                OrderInfo orderInfo = new OrderInfo();
                                orderInfo.setStatus(status);

                                List<Map<String, Object>> queryByEmployId = errandService
                                    .queryByEmployId(
                                        driver.getId(), "present", null, null);

                                driver.setErrandType(
                                    queryByEmployId.get(0).get("orderType").toString());
                                driver.setJobContent(jobContent);
                                driver.setOrderInfo(orderInfo);
                            }
                        } else if (Driver.DRIVER_JOBSTATUS_FREIGHT
                            .equals(driver.getJobStatus())) {// 货运
                            List<com.ybkj.daijia.server.freight.Order> freightorders = freightService
                                .findActivedOrdersByDriver(driver.getId());
                            if (!CollectionUtils.isEmpty(freightorders)) {
                                com.ybkj.daijia.server.freight.Order freightOrder = freightorders
                                    .get(0);
                                OrderInfo orderInfo = new OrderInfo();
                                orderInfo.setOrderNumber(freightOrder.getOrderNo());
                                orderInfo.setDate(format.format(freightOrder.getStartTime()));
                                orderInfo.setFromPlace(freightOrder.getStartAddress());
                                orderInfo.setToPlace(freightOrder.getDestination());
                                orderInfo.setStatus(freightOrder.getStatus());

                                driver.setOrderInfo(orderInfo);
                            }
                        } else if (Driver.DRIVER_JOBSTATUS_ZHUANXIAN
                            .equals(driver.getJobStatus())) {// 城际专线
                            List<com.ybkj.daijia.server.zhuanxian.Order> zhuanxianorders = zhuanxianService
                                .findActivedOrdersByDriver(driver.getId());
                            if (!CollectionUtils.isEmpty(zhuanxianorders)) {
                                String jobContent = "";
                                long seats = 0;
                                for (com.ybkj.daijia.server.zhuanxian.Order zhuanxianorder : zhuanxianorders) {
                                    jobContent += "(" + zhuanxianorder.getOrderTypeStr() + ")"
                                        + zhuanxianorder.getStartAddress() + " 至 " + zhuanxianorder
                                        .getEndAddress();
                                    if (!zhuanxianorder.isYuyue()) {
                                        seats += (zhuanxianorder.getPeopleNumber() == null ? 0
                                            : zhuanxianorder
                                                .getPeopleNumber());
                                    } else {
                                        jobContent += "<br/>(预约："
                                            + new SimpleDateFormat("yyyy-MM-dd HH:mm")
                                            .format(zhuanxianorder
                                                .getServerTime()) + ")";
                                    }
                                    jobContent += ",";
                                }

                                driver.setJobContent(jobContent);
                                driver.setSeatsNow(seats);
                                if (null != driver.getZhuanxianCarId()) {
                                    com.ybkj.daijia.server.zhuanxian.Car car = zhuanxianService
                                        .findCar(driver
                                            .getZhuanxianCarId());
                                    if (null != car) {
                                        driver
                                            .setSeatsTotal(Long.valueOf(car.getRidepeopleNumber()));
                                    }
                                }

                            }
                        }

                    }
                }
            }

            dataMap.put("orders", orderMapList);
            dataMap.put("drivers", driverList);
            List<Driver> lixianDriverList = new ArrayList<>();
            for (Driver driver : driverList) {
                //离线
                if (0 == driver.getStatus()) {
                    lixianDriverList.add(driver);
                }
            }
            dataMap.put("lixianAmounts", lixianDriverList.size());

            return dataMap;

        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "deviceInfo", method = RequestMethod.POST)
    public @ResponseBody
    Result<String> deviceInfo(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Result<String> result = new Result<String>();

        if (subject.isPermitted("driver")) {
            try {
                Driver driver = driverService.findOne(id);

                // 发送设备推送
                PushDataV4 pushDataV4 = new PushDataV4();
                pushDataV4.setCode("0X09");
                Map<String, String> extra = new HashMap<String, String>();
                extra.put("content", "获取设备信息");
                pushDataV4.setExtra(extra);

                boolean getuiOnline = false;
                if (StringUtils.isNotBlank(driver.getUserID())) {
                    getuiOnline = GeTuiEmployV4
                        .getClientOnline(driver.getUserID(), settingUtils.get());
                }

                if (getuiOnline) {
                    GeTuiEmployV4.push(driver, pushDataV4, settingUtils.get());
                } else {
                    if (StringUtils.isNotBlank(driver.getRegistrationId())) {
                        JiGuangEmployV4.push(driver, pushDataV4, settingUtils.get());
                    }
                }

                result.setSuccess(true);
                return result;

            } catch (Exception e) {
                e.printStackTrace();
                result.setSuccess(false);
                result.setMessage("推送失败2" + e.getMessage());
                return result;
            }
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "changepassword", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> changepassword(Long id, final String password) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driveredit")) {
            Result<Integer> result = new Result<Integer>();
            final Driver driver = driverService.findOne(id);
            Sha256Hash hash = new Sha256Hash(String.valueOf(password));
            driver.setPassword(hash.toBase64());
            driverService.updateByPassword(hash.toBase64(), driver.getId());

            DriverLogin driverLogin = driverLoginService.selectByDriver(id);
            if (null != driverLogin) {
                Calendar calendar = Calendar.getInstance();
                driverLogin.setDeathDate(calendar.getTime());
                driverLoginService.update(driverLogin);
            }

            result.setSuccess(true);

            String detail =
                "【%s】修改了服务人员【" + driver.getUsername() + "(" + driver.getRealname() + "】密码。";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);
            Company driverCompany = companyService.findOne(driver.getCompanyId());
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            if (!main.getId().equals(driverCompany.getId()) && setting.isSmsMainCompany()) {
                driverCompany = main;
            }
            final Company finalCompany = driverCompany;
            taskExecutor.execute(new Runnable() {
                public void run() {
                    int ret = -99;
                    try {
                        String chenghu = "先生";
                        if (driver.getGender().equals("女")) {
                            chenghu = "女士";
                        }
                        SmsTemplet templet = smsService.findByAlias(finalCompany.getId(),
                            SmsType.driverChangePassword);
                        if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                            ret = smsService.sendSms(driver.getPhone(), "driverChangePassword",
                                "{\"服务人员名\":\"" + driver.getName() + "\",\"称呼\":\"" + chenghu
                                    + "\",\"服务人员账号\":\"" + driver.getUsername() + "\",\"密码\":\""
                                    + password
                                    + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    log.debug("修改服务人员密码短信发送结果：" + ret + " 密码：" + password);
                }
            });

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "diaodu/mapmodev3", method = RequestMethod.GET)
    public ModelAndView mapmodev3() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("dispatch")) {
            ModelAndView mv = new ModelAndView();

            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();

            Company company = companyService.findOne(principal.getCompanyId());

            mv.addObject("longitude", company.getLongitude());
            mv.addObject("latitude", company.getLatitude());

            mv.setViewName("diaodu/mapmodev3");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    /***
     * 获取推荐司机 包括所有订单类型
     * @record zhyu
     * @param orderId
     * @param orderType
     * @return
     */
    @RequestMapping(value = "tuijianDiaoduDrivers", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> tuijianDiaoduDrivers(Long orderId, String orderType) {

        return driverService.tuijianDiaoduDrivers(orderId, orderType);

    }

    @RequestMapping(value = "queryDiaoduDrivers", method = RequestMethod.GET)
    public @ResponseBody
    List<Driver> queryDiaoduDrivers(String keyword, Long orderId,
        String orderType) {

        return driverService.queryDiaoduDrivers(keyword, orderId, orderType);

    }

    public boolean exists(String username, Long id) {
        Driver driver = driverService.findByUsername(username);
        if (null != driver) {
            if (null != id && id.equals(driver.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean idCardExists(String idCard, Long id) {
        Driver driver = driverService.findByIdCard(idCard);
        if (null != driver) {
            if (null != id && id.equals(driver.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean phoneExists(String phone, Long id) {
        Driver driver = driverService.findByPhone(phone);
        if (null != driver) {
            if (null != id && id.equals(driver.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        dataBinder.setAutoGrowCollectionLimit(1024);

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

    private String toPinyin(String zh) {

        if (StringUtils.isBlank(zh)) {
            return null;
        }

        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        char ch[] = zh.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ch.length; i++) {
            if (Character.toString(ch[i]).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String pinyinStrArray[] = PinyinHelper
                        .toHanyuPinyinStringArray(ch[i], outputFormat);

                    if ((null != pinyinStrArray) && (pinyinStrArray.length > 0)) {
                        sb.append(pinyinStrArray[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                sb.append(ch[i]);
            }
        }
        return sb.toString();
    }

    /**
     * 后台点击服务人员按钮
     * @record zhyu
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("driver")) {
            ModelAndView mv = new ModelAndView();

            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            } else {
                mv.addObject("company", companyService.findOne(principal.getCompanyId()));
            }
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (serviceSetting.isJgpt()) {
                mv.addObject("isUpPlatformInfo", settingUtils.get().isUpPlatformInfo());
            } else {
                mv.addObject("isUpPlatformInfo", false);
            }
            mv.addObject("isDriverBindPhone", settingUtils.get().isDriverBindPhone());
            Boolean isJgpt = serviceSetting.isJgpt();
            mv.addObject("isJgpt", isJgpt);
            mv.setViewName("driver/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("driverListData")
    public @ResponseBody
    Page<Map<String, Object>> driverListData(HttpServletRequest req,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "virtual") BigDecimal virtual,
        @RequestParam(required = false, value = "companyId") Long[] companyId,
        @RequestParam(required = false, value = "isFreeze") Boolean isFreeze,
        @RequestParam(required = false, value = "type") String[] type,
        @RequestParam(required = false, value = "isPlatform") Integer[] isPlatform,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "isLeague") Boolean isLeague) {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {

            if (null != type && type.length == 0) {
                type = null;
            }
            if (null != status && status.length == 0) {
                status = null;
            }

            Date start = null;
            Date end = null;

            if (!StringUtils.isEmpty(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(start);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);

                    start = calendar.getTime();
                } catch (ParseException e) {
                    if (log.isErrorEnabled()) {
                        log.error("时间处理错误", e);
                    }
                }

            }

            if (!StringUtils.isBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd");

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(end);
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);

                    end = calendar.getTime();
                } catch (ParseException e) {
                    if (log.isErrorEnabled()) {
                        log.error("时间处理错误", e);
                    }
                }

            }
            Page<Map<String, Object>> result = driverService
                .driverlistData(name, phone, username, start,
                    end, companyId, virtual, isFreeze, type, status, isPlatform, isLeague);

            if (!CollectionUtils.isEmpty(result.getContent())) {
                String bathPath = getBasePath(req);
                for (Map<String, Object> map : result.getContent()) {
                    String photo = (String) map.get("photo");
                    if (StringUtils.isNotBlank(photo)) {
                        File f = new File(bathPath, "upload/driver/" + photo);
                        if (f.exists()) {
                            map.put("photoExixts", true);
                        }
                    }
                }
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("loginlist")
    public ModelAndView loginlist() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("driverloginrecord")) {
            ModelAndView mv = new ModelAndView();

            if (principal.isCompanyType()) {
                mv.addObject("companys", companyService.findAll());
            }

            mv.setViewName("driver/loginlist");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping("loginListData")
    public @ResponseBody
    Page<DriverLoginRecord> loginListData(HttpServletRequest req,
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "companyId") Long[] companyId) {
        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driverloginrecord")) {

            Page<DriverLoginRecord> result = driverService.loginListData(param, companyId);

            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "exportDriver", method = RequestMethod.GET)
    public void exportDriver(@RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime,
        @RequestParam(required = false, value = "virtual") BigDecimal virtual,
        @RequestParam(required = false, value = "companyId") Long[] companyId,
        @RequestParam(required = false, value = "isFreeze") Boolean isFreeze,
        @RequestParam(required = false, value = "type") String[] type,
        @RequestParam(required = false, value = "status") Integer[] status,
        @RequestParam(required = false, value = "isPlatform") Integer[] isPlatform,
        HttpServletRequest req, HttpServletResponse response) throws IOException {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (subject.isPermitted("driverExport")) {

            if (null != type && type.length == 0) {
                type = null;
            }
            if (null != status && status.length == 0) {
                status = null;
            }
            if (null != isPlatform && isPlatform.length == 0) {
                isPlatform = null;
            }
            if (null != companyId && companyId.length == 0) {
                companyId = null;
            }

            Date start = null;
            Date end = null;

            if (!StringUtils.isEmpty(startTime)) {
                try {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(start);
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);

                    start = calendar.getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }

            if (!StringUtils.isBlank(endTime)) {
                try {
                    end = DateUtils.parseDate(endTime, "yyyy-MM-dd");

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(end);
                    calendar.set(Calendar.HOUR_OF_DAY, 23);
                    calendar.set(Calendar.MINUTE, 59);
                    calendar.set(Calendar.SECOND, 59);

                    end = calendar.getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }
            List<Driver> list = driverService.selectDriverList(name, phone, username, start, end,
                companyId, virtual, isFreeze, type, status, isPlatform, null);

            List<List<String>> rowlist = new ArrayList<List<String>>();
            String[] head = new String[20];
            head[0] = ("姓名");
            head[1] = ("是否已上传监管平台");
            head[2] = ("工号");
            head[3] = ("昵称");
            head[4] = ("手机号");
            head[5] = ("余额(元)");
            head[6] = ("员工类型");
            head[7] = ("状态");
            head[8] = ("代驾");
            head[9] = ("专车");
            head[10] = ("跑腿");
            head[11] = ("货运");
            head[12] = ("城际专线");
            head[13] = ("等级");
            head[14] = ("APP版本");
            head[15] = ("身份证号");
            head[16] = ("性别");
            head[17] = ("入职时间");
            if (principal.isCompanyType()) {
                head[18] = ("所属公司");
            }
            head[19] = ("上传时间");

            for (Driver a : list) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                List<String> celllist = new ArrayList<String>();
                DriverChoseLevel driverChoseLevel = driverChoseLevelService.findByDriverAndCompany(
                    a.getId(), a.getCompanyId());
                if (null != driverChoseLevel) {
                    a.setDriverLevel(
                        driverLevelService.findOne(driverChoseLevel.getDriverlevelId()));
                }
                DriverChoseLevelCar driverChoseLevelCar = driverChoseLevelCarService
                    .findByDriverAndCompany(a.getId(), a.getCompanyId());
                if (null != driverChoseLevelCar) {
                    a.setDriverLevelZhuan(
                        driverLevelService.findOne(driverChoseLevelCar.getDriverlevelId()));
                }
                DriverChoseLevelPaotui driverChoseLevelPaotui = driverChoseLevelPaotuiService
                    .findByDriverAndCompany(a.getId(), a.getCompanyId());
                if (null != driverChoseLevelPaotui) {
                    a.setDriverLevelPao(
                        driverLevelService.findOne(driverChoseLevelPaotui.getDriverlevelId()));
                }
                DriverChoseLevelFreight driverChoseLevelFreight = driverChoseLevelFreightService
                    .findByDriverAndCompany(a.getId(), a.getCompanyId());
                if (null != driverChoseLevelFreight) {
                    a.setDriverLevelFreight(driverLevelService.findOne(driverChoseLevelFreight
                        .getDriverlevelId()));
                }
                if (null != a.getZhuanxianCarId()) {
                    List<DriverChoseLevelZhuanxian> driverChoseLevelZhuanxians = driverChoseLevelZhuanxianService
                        .findByDriver(a.getId());
                    if (!CollectionUtils.isEmpty(driverChoseLevelZhuanxians)) {
                        a.setDriverLevelZhuanxian(
                            driverLevelService.findOne(driverChoseLevelZhuanxians.get(0)
                                .getDriverlevelId()));
                    }
                }

                celllist.add(a.getRealname());
                celllist.add((a.getUpStatus()) == 1 ? "是" : "否");
                celllist.add(a.getUsername());
                celllist.add(a.getName());
                celllist.add(UseAllDataUtil.useAllDataDriver(a.getPhone()));
                celllist.add(a.getVirtual().toString());
                celllist.add(a.getType());
                if (a.getIsFreeze()) {
                    celllist.add("冻结");
                } else if (a.getStatus().equals(Driver.DRIVER_JOBSTATUS_DAIJIA)) {
                    celllist.add("下线");
                } else if (a.getStatus().equals(Driver.DRIVER_JOBSTATUS_ZHUANCHE)) {
                    celllist.add("空闲");
                } else if (a.getStatus().equals(Driver.DRIVER_JOBSTATUS_PAOTUI)) {
                    celllist.add("派单");
                } else if (a.getStatus().equals(Driver.DRIVER_JOBSTATUS_FREIGHT)) {
                    celllist.add("忙碌");
                }
                if (a.getDriverJobType().contains("daijia")) {
                    celllist.add(
                        "含（" + (a.getDriverLevel() == null ? "无" : a.getDriverLevel().getName())
                            + "）");
                } else {
                    celllist.add("--");
                }
                if (a.getDriverJobType().contains("zhuanche")) {
                    celllist.add("含（"
                        + (a.getDriverLevelZhuan() == null ? "无"
                        : a.getDriverLevelZhuan().getName()) + "）");
                } else {
                    celllist.add("--");
                }
                if (a.getDriverJobType().contains("paotui")) {
                    celllist.add("含（"
                        + (a.getDriverLevelPao() == null ? "无" : a.getDriverLevelPao().getName())
                        + "）");
                } else {
                    celllist.add("--");
                }
                if (a.getDriverJobType().contains("freight")) {
                    celllist.add("含（"
                        + (a.getDriverLevelFreight() == null ? "无"
                        : a.getDriverLevelFreight().getName())
                        + "）");
                } else {
                    celllist.add("--");
                }
                if (a.getDriverJobType().contains("zhuanxian")) {
                    celllist.add("含（"
                        + (a.getDriverLevelZhuanxian() == null ? "无"
                        : a.getDriverLevelZhuanxian().getName())
                        + "）");
                } else {
                    celllist.add("--");
                }
                celllist.add(a.getDriverGrade() != null ? a.getDriverGrade().getName() : "无等级");
                celllist.add(a.getAppVersion() != null ? a.getAppVersion() : "未上传");
                celllist.add(a.getIdCard());
                celllist.add(a.getGender());
                celllist.add(sdf.format(a.getJobTime()));
                if (principal.isCompanyType()) {
                    celllist.add(companyService.findOne(a.getCompanyId()).getAbbreviation());
                }
                celllist.add(a.getPosUpdated() != null ? sdf.format(a.getPosUpdated()) : "未上传");

                rowlist.add(celllist);

            }

            ExcelUtil.export(req, response, head, rowlist);
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("recordlist")
    public ModelAndView recordlist() {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("driver")) {
            ModelAndView mv = new ModelAndView();

            mv.setViewName("driver/recordlist");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("recordListData")
    public @ResponseBody
    Page<PhoneRecord> recordListData(
        @RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driver")) {

            Page<PhoneRecord> result = driverService.queryRecordlist(param);
            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping("importDriver")
    @ResponseBody
    public Map<String, Object> importCar(@RequestParam("driverExcel") MultipartFile file)
        throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();
            Pattern patternPhone = Pattern.compile("^[0-9]{1,15}$");
            Pattern illegalPattern = Pattern.compile("^([\u4e00-\u9fa5]+|[a-zA-Z0-9]+)$");

            Workbook wb = null;
            try {

                wb = new HSSFWorkbook(file.getInputStream());
            } catch (Exception e) {
                wb = new XSSFWorkbook(file.getInputStream());
                // wb = WorkbookFactory.create(is);
            }
            Sheet sheet = wb.getSheetAt(0);
            int rowNum = sheet.getLastRowNum();// 得到总行数
            if (rowNum > 2001) {
                map.put("msg", "导入数量过大,请限制数量在2000以内");
                map.put("rowNum", rowNum);
                return map;
            }
            if (rowNum <= 0) {
                map.put("msg", "Excel文件内容不正确");
                map.put("rowNum", rowNum);
                return map;
            }
            Row row = sheet.getRow(0);
            int colNum = row.getPhysicalNumberOfCells(); // 列的数量
            SimpleDateFormat sdf = DateTimeUtils.DATE_FORMAT_DATE;
            List<Driver> list = new LinkedList<Driver>();
            List<Integer> realnameIndexs = new LinkedList<>();
            List<Integer> usernameIndexs = new LinkedList<>();
            List<Integer> nameIndexs = new LinkedList<>();
            List<Integer> idCardIndexs = new LinkedList<>();
            List<Integer> phoneIndexs = new LinkedList<>();
            List<Integer> typeIndexs = new LinkedList<>();
            List<Integer> licenseTimeIndexs = new LinkedList<>();
            Map<Integer, Integer> repeatPhone = new HashMap<>();
            Map<Integer, Integer> repeatUsername = new HashMap<>();
            Map<Integer, Integer> repeatIdCard = new HashMap<>();
            for (int i = 1; i <= rowNum; i++) {
                row = sheet.getRow(i);
                int j = 0;
                boolean flag = false;
                Driver driver = new Driver();
                while (j < colNum) {

                    try {
                        // 每个单元格的数据内容用"-"分割开，以后需要时用String类的replace()方法还原数据
                        // 也可以将每个单元格的数据设置到一个javabean的属性中，此时需要新建一个javabean
                        // str += getStringCellValue(row.getCell((short) j)).trim() +
                        // "-";
                        if (row == null || row.getCell(j) == null) {
                            j++;
                            flag = true;
                        } else {

                            String str = getCellFormatValue(row.getCell(j)).trim();
                            if (StringUtils.isNotBlank(str)) {
                                switch (j) {
                                    case 0:
                                        if (illegalPattern.matcher(str).matches()) {
                                            driver.setRealname(str);// 真实姓名
                                        } else {
                                            realnameIndexs.add(i);
                                        }
                                        break;
                                    case 1:
                                        if (illegalPattern.matcher(str).matches() && (!exists(str,
                                            null))) {
                                            driver.setUsername(str);// 工号
                                        } else {
                                            usernameIndexs.add(i);
                                        }
                                        break;
                                    case 2:
                                        if (illegalPattern.matcher(str).matches() && StringUtils
                                            .isNotBlank(str)) {
                                            driver.setName(str);// 昵称
                                        } else {
                                            nameIndexs.add(i);
                                        }
                                        break;
                                    case 3:
                                        if (patternPhone.matcher(str).matches() && (!phoneExists(
                                            str, null))) {
                                            driver.setPhone(str);// 手机号
                                        } else {
                                            phoneIndexs.add(i);
                                        }
                                        break;
                                    case 4:
                                        if (str.equals("兼职") || str.equals("全职")) {
                                            driver.setType(str);// 员工类型
                                        } else {
                                            typeIndexs.add(i);
                                        }
                                        break;
                                    case 5:
                                        if (!idCardExists(str, null)) {
                                            driver.setIdCard(str);// 身份证号
                                            String password = str
                                                .substring(str.length() - 4, str.length());
                                            Sha256Hash hash = new Sha256Hash(
                                                String.valueOf(password));
                                            driver.setPassword(hash.toBase64());
                                        } else {
                                            idCardIndexs.add(i);
                                        }

                                        break;
                                    case 6:
                                        driver.setGender(str);// 性别
                                        break;
                                    case 7:
                                        driver.setPressingName(str);// 紧急联系人
                                        break;
                                    case 8:
                                        driver.setPressingPhone(str);// 紧急电话
                                        driver.setEmergency(driver.getPressingName() + "+" + driver
                                            .getPressingPhone());// (首页必填)紧急联系人
                                        break;
                                    case 9:
                                        driver.setLicenseTime(sdf.parse(str));// 领证时间
                                        break;
                                    case 10:
                                        String string = str;
                                        Integer integer = Integer.valueOf(string);
                                        driver.setDriveTimes(Integer.valueOf(integer));// 服务次数
                                        break;
                                    case 11:
                                        driver.setStarLevel(Double.valueOf(str));// 服务人员评分
                                        break;
                                    case 12:
                                        driver.setLicenseType(str);// 驾照类型
                                        break;
                                    case 13:
                                        driver.setIntroducer(str);// 介绍人
                                        break;
                                    case 14:
                                        driver.setHeight(Integer.valueOf(str));// 身高(cm)
                                        break;
                                    case 15:
                                        driver.setDriverCensus(str);// 户口登记机关
                                        break;
                                    case 16:
                                        driver.setOrigin(str);// 籍贯
                                        break;
                                    case 17:
                                        driver.setAddress(str);// 家庭住址
                                        break;
                                    case 18:
                                        driver.setDriverLicenseNo(str);// 机动车驾驶证号
                                        break;
                                    case 19:
                                        driver.setDriverLicenseId(str);// 机动车驾档编号
                                        break;
                                    case 20:
                                        driver.setBirthday(sdf.parse(str));// 出生日期
                                        break;
                                    case 21:
                                        driver.setConcatAddress(str);// 驾驶员驾驶员通信地址
                                        break;
                                    case 22:
                                        driver.setTrafficViolation(Integer.valueOf(str));// 交通违章次数
                                        break;
                                    case 23:
                                        driver.setDriverLicenseValid(sdf.parse(str));// 驾驶证有效期起始时间
                                        break;
                                    case 24:
                                        driver
                                            .setDriverLicenseInvalid(sdf.parse(str));// 驾驶证有效期限结束时间
                                        break;
                                    case 25:
                                        driver.setTaxiLicenseNo(str);// 网络预约出租车驾驶员证编号
                                        break;
                                    case 26:
                                        driver.setTaxiLicenseOrg(str);// 资格证发证机构
                                        break;
                                    case 27:
                                        driver.setTaxiLicenseRegister(str);// 资格证发证日期
                                        break;
                                    case 28:
                                        driver.setTaxiLicenseRecive(str);// 初次领取资格证日期
                                        break;
                                    case 29:
                                        driver.setTaxiLicenseValid(str);// 资格证有效起始日期
                                        break;
                                    case 30:
                                        driver.setTaxiLicenseInvalid(str);// 资格证有效截止日期
                                        break;
                                    case 31:
                                        driver.setContractCompany(str);// 合同（或协议）签署公司
                                        break;
                                    case 32:
                                        driver.setContractValid(sdf.parse(str));// 合同有效期起始时间
                                        break;
                                    case 33:
                                        driver.setContractInvalid(sdf.parse(str));// 合同有效期结束时间
                                        break;
                                    case 34:
                                        driver.setEmergencyAddress(str);// 紧急情况联系人通信地址
                                        break;
                                    case 35:
                                        driver.setSeviceReview(Double.valueOf(str));// 驾驶员服务质量信誉考核结果
                                        break;
                                }
                                driver.setCompanyId(principal.getCompanyId());
                                driver.setIsFreeze(false);
                                driver.setStatus(Driver.DRIVER_OFFLINE);
                                driver.setWorkCar(false);
                                if (j >= 10) {// 如果使用的是监管平台上传模板，导入以下默认值
                                    Company company = companyService
                                        .findOne(principal.getCompanyId());
                                    driver.setAddressCode(company.getAdministrativeDivisionNo());
                                    driver.setAddressCodeArr(
                                        company.getAdministrativeDivisionNoArr());
                                    driver.setNationality("中国");
                                    driver.setNation("1");
                                    driver.setMarital(1);
                                    driver.setEducation("21");
                                    driver.setForeignLanguageAbility("英语四级");
                                    driver.setCruise(0);
                                    driver.setInBlacklist(false);
                                    driver.setPhoneOperator("CHINA_MOBILE");
                                    driver.setMapType("0");
                                    driver.setCommercialType("1");
                                    driver.setDriverJobType("zhuanche");
                                }

                            } else {
                                flag = true;
                            }
                        }
                        j++;

                    } catch (Exception e) {
                        e.printStackTrace();
                        map.put("success", false);
                        map.put("message", "导入失败，请检查模板是否正确");
                        return map;

                    }

                }
                if (flag) {
                    continue;
                }
                int length = list.size();
                int tempPhoneIndex = -1;
                int tempIdCardIndex = -1;
                int tempUsernameIndex = -1;
                if (length >= 1) {
                    for (int index = 0; index < length; index++) {
                        if (StringUtils.isNotBlank(list.get(index).getUsername())) {
                            if (list.get(index).getUsername()
                                .equalsIgnoreCase(driver.getUsername())) {
                                tempUsernameIndex = index;
                                break;
                            }
                        }
                        if (StringUtils.isNotBlank(list.get(index).getPhone())) {
                            if (list.get(index).getPhone().equalsIgnoreCase(driver.getPhone())) {
                                tempPhoneIndex = index;
                                break;
                            }
                        }
                        if (StringUtils.isNotBlank(list.get(index).getIdCard())) {
                            if (list.get(index).getIdCard().equalsIgnoreCase(driver.getIdCard())) {
                                tempIdCardIndex = index;
                                break;
                            }
                        }
                    }
                }

                if (tempPhoneIndex != -1) {
                    repeatPhone.put(i + 1, tempPhoneIndex + 2);
                }
                if (tempIdCardIndex != -1) {
                    repeatIdCard.put(i + 1, tempIdCardIndex + 2);
                }
                if (tempUsernameIndex != -1) {
                    repeatUsername.put(i + 1, tempUsernameIndex + 2);
                }
                if (tempUsernameIndex == -1 && tempIdCardIndex == -1 && tempPhoneIndex == -1) {
                    list.add(driver);
                }

            }

            if (list.size() == 0) {
                map.put("success", false);
                map.put("message", "导入失败，请检查模板是否正确");
                return map;
            }

            if (CollectionUtils.isEmpty(realnameIndexs) && CollectionUtils.isEmpty(usernameIndexs)
                && CollectionUtils.isEmpty(nameIndexs) && CollectionUtils.isEmpty(idCardIndexs)
                && CollectionUtils.isEmpty(phoneIndexs) && CollectionUtils.isEmpty(typeIndexs)
                && CollectionUtils.isEmpty(licenseTimeIndexs) && repeatPhone.isEmpty()
                && repeatIdCard.isEmpty() && repeatUsername.isEmpty()) {

                int i = driverService.insertList(list);
                if (i != 0) {
                    map.put("success", true);
                    map.put("message", "导入成功");
                } else {
                    map.put("success", false);
                    map.put("message", "导入失败");
                }
            }

            map.put("realnameIndexs", realnameIndexs);
            map.put("usernameIndexs", usernameIndexs);
            map.put("nameIndexs", nameIndexs);
            map.put("idCardIndexs", idCardIndexs);
            map.put("phoneIndexs", phoneIndexs);
            map.put("typeIndexs", typeIndexs);
            map.put("licenseTimeIndexs", licenseTimeIndexs);
            if (!repeatPhone.isEmpty()) {
                map.put("repeatPhone", repeatPhone);
            }
            if (!repeatIdCard.isEmpty()) {
                map.put("repeatIdCard", repeatIdCard);
            }
            if (!repeatUsername.isEmpty()) {
                map.put("repeatUsername", repeatUsername);
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "导入失败，请检查模板是否正确");
            return map;
        }

        return map;
    }

    @RequestMapping("checkDriver")
    @ResponseBody
    public Result ckeckDriver(@RequestParam("ids") Long[] ids, HttpServletRequest request) {
        Result result = new Result();
        try {
            HttpSession session = request.getSession();
            Map<String, Object> data = driverService
                .checkDriver(ids, session, getBasePath(request));
            result.setSuccess(true);
            result.setResult(data);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        return result;
    }

    private String getStringCellValue(HSSFCell cell) {
        String strCell = "";
        switch (cell.getCellType()) {
            case HSSFCell.CELL_TYPE_STRING:
                strCell = cell.getStringCellValue();
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                strCell = String.valueOf(cell.getNumericCellValue());
                break;
            case HSSFCell.CELL_TYPE_BOOLEAN:
                strCell = String.valueOf(cell.getBooleanCellValue());
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                strCell = "";
                break;
            default:
                strCell = "";
                break;
        }
        if (strCell.equals("") || strCell == null) {
            return "";
        }
        if (cell == null) {
            return "";
        }
        return strCell;
    }

    @RequestMapping("uploadDriver")
    @ResponseBody
    public Result uploadDriver(@RequestParam("ids") Long[] ids, HttpServletRequest request) {
        Result result = new Result();
        // try {
        driverService.uploadDriver(ids, getBasePath(request));
        result.setSuccess(true);
        // } catch (Exception e) {
        // e.printStackTrace();
        // result.setSuccess(false);
        // result.setMessage("内部服务器错误("+e.getMessage()+")");
        // }
        return result;
    }

    /**
     * 获取单元格数据内容为日期类型的数据
     *
     * @param cell Excel单元格
     * @return String 单元格数据内容
     */
    private String getDateCellValue(HSSFCell cell) {
        String result = "";
        try {
            int cellType = cell.getCellType();
            if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
                Date date = cell.getDateCellValue();
                result =
                    (date.getYear() + 1900) + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            } else if (cellType == HSSFCell.CELL_TYPE_STRING) {
                String date = getStringCellValue(cell);
                result = date.replaceAll("[年月]", "-").replace("日", "").trim();
            } else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
                result = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据HSSFCell类型设置数据
     *
     * @param cell
     * @return
     */
    private String getCellFormatValue(Cell cell) {
        String cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                // 如果当前Cell的Type为NUMERIC
                case HSSFCell.CELL_TYPE_NUMERIC:
                case HSSFCell.CELL_TYPE_FORMULA: {
                    // 判断当前的cell是否为Date
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式

                        // 方法1：这样子的data格式是带时分秒的：2011-10-12 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();

                        // 方法2：这样子的data格式是不带带时分秒的：2011-10-12
                        Date date = cell.getDateCellValue();
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        cellvalue = sdf.format(date);

                    }
                    // 如果是纯数字
                    else {
                        // 取得当前Cell的数值
                        // cellvalue = String.valueOf(cell.getNumericCellValue());
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        cellvalue = cell.getStringCellValue();
                    }
                    break;
                }
                // 如果当前Cell的Type为STRIN
                case HSSFCell.CELL_TYPE_STRING:
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                // 默认的Cell值
                default:
                    cellvalue = " ";
            }
        } else {
            cellvalue = "";
        }
        if (null == cellvalue) {
            cellvalue = "";
        }
        return cellvalue;

    }
}
